如何使用webdriver在Chrome中打开新窗口而不是新标签页?

5
为了自动化我的测试应用程序,我需要在新窗口中打开一些链接,而不是在选项卡中打开。请记住,我没有显式地在新选项卡中打开链接,而是我的网络应用程序在单击链接后自动将用户引导到新选项卡。 为什么我要这样做? 因为在Chrome浏览器上运行测试会关闭主选项卡并保持新打开的选项卡处于打开状态,这最终会导致测试失败。因此,最终目的是打开新窗口而不是选项卡,并使用driver.getWindowHandles()来正确地处理它。 我已经做了什么? 我试图在Chrome中找到一些能力设置或配置文件,自动打开应该在选项卡中打开的链接的解决方案。但并没有找到任何令人信服的解决方案,大多数建议是CTRL + 单击链接。

你能试试这个吗?看看它是否适用于你。https://dev59.com/fWQm5IYBdhLWcg3wyhnk - A user
@Pri 谢谢,首先我需要这个解决方案适用于Chrome浏览器,其次我不想使用webdriver在新窗口中打开链接。浏览器会决定在哪里打开链接。因此,我需要在Chrome中进行某种配置,以便始终在新窗口中打开应该在新标签页中打开的链接。 - Priyanshu
这个问题很有趣。你能右键点击并从菜单中选择选项吗?所以答案仍然不适用于Chrome。但我仍然觉得右键点击有帮助。https://dev59.com/RWgu5IYBdhLWcg3wTFWi - A user
我需要一个通用的解决方案,因为我不确定我的应用程序中有多少这样的链接。可能只需在浏览器级别上进行配置即可帮助我实现所有此类链接的目标。 - Priyanshu
2
你尝试过发送键 Control + n 吗?这会启动一个新窗口,然后在新窗口中打开链接。 - Naveen Kumar R B
如果你修改DOM并使用这个问题的答案,它会起作用:https://dev59.com/CmYq5IYBdhLWcg3w30Xc - Happy Bird
2个回答

2

虽然我不是网页设计专家,但我可以提出以下方案:

// Get required page
// Excecute below JavaScript with JavaScriptExecutor
var reference = document.querySelector('a#someID').getAttribute('href'); // You can use your specific CSS Selector instead of "a#someID"
document.querySelector('a#someID').setAttribute("onclick", "window.open('" + reference + "', '', 'width=800,height=600')")
document.querySelector('a#someID').removeAttribute('href')
// Find target link
// Click on it

这段代码应该可以让你修改目标网页元素的HTML源代码,强制在新的浏览器窗口中打开它。
请注意,使用此代码后,元素的外观将会被更改,直到页面刷新为止。
顺便提一句,由于你没有说明所用编程语言,所以无法提供完整的实现代码...不过,以下是Python实现的示例代码:
from selenium import webdriver as web

dr = web.Chrome()
dr.get('https://login.live.com/login.srf?&wreply=https%3a%2f%2foutlook.live.com%2fowa%2f%3fnlp%3d1%26realm%3dlogin.live.com')

dr.execute_script("""
    var reference = document.querySelector('a#ftrTerms').getAttribute('href');
    document.querySelector('a#ftrTerms').setAttribute("onclick", "window.open('" + reference + "', '', 'width=800,height=600')")
    document.querySelector('a#ftrTerms').removeAttribute('href')
    """)
link = dr.find_element_by_id('ftrTerms')
link.click()

2

由于Chrome浏览器中没有任何标志/设置/功能可以在新窗口中打开链接而不是新选项卡,因此我使用了Chrome扩展程序来实现这一点,通过WebDriver。

为什么要这样做?

因为我的测试在Firefox上运行良好,并且我不知道套件中有多少WebElements会在Chrome浏览器的新选项卡中打开。该套件也非常庞大,因此对其核心页面类进行任何更改可能会破坏所有测试。除此之外,在元素级别上更改代码将非常耗时,最重要的是不是通用解决方案。

我做了什么?

  1. I used a chrome extension New Tab New Window, which opens all the new tabs into a new window.
  2. Downloaded the CRX file of this extension using an extension Get CRX.
  3. Set the CRX file as a capability of Chrome.

    ChromeOptions options = new ChromeOptions();
    options.addExtensions(new File("pathOfCRXFile"));
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();         
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    WebDriver driver = new ChromeDriver(capabilities);
    

以上代码将把所有新标签页转换为新窗口。因此,每当驱动程序单击任何在新选项卡中打开的链接时,它都会在新窗口中打开。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接