【问题标题】:How to open new window instead of new tab in chrome using webdriver?如何使用 webdriver 在 chrome 中打开新窗口而不是新选项卡?
【发布时间】:2017-05-19 17:59:08
【问题描述】:

为了自动化我的测试应用程序,我需要在新窗口而不是选项卡中打开几个链接。请记住,我并没有明确打开新标签中的链接,它是我的网络应用程序,它会在点击链接后自动将用户引导到新标签中。

我为什么要这样做?

因为在 chrome 浏览器上运行测试会关闭主选项卡并保持打开新打开的选项卡。最终无法通过测试。因此最终目的是打开新窗口而不是选项卡并使用driver.getWindowHandles()正确处理它。

到目前为止我做了什么?

我试图在 Chrome 中找到某种功能设置或配置文件,它会自动在新窗口中打开应该在选项卡中打开的链接。但没有找到任何令人信服的解决方案,大多数建议是 CTRL+CLICK在链接上。

【问题讨论】:

  • 你能试试这个吗?让我们看看它是否适合你.. *.com/questions/17325629/…
  • @Pri 谢谢,首先我需要这个 Chrome 解决方案,其次我不想使用 webdriver 在新窗口中打开链接。它的浏览器决定在哪里打开链接。所以我需要在 chrome 中进行某种配置,它总是在新窗口中打开应该在新选项卡中打开的链接。
  • 这个问题很有趣。您可以右键单击并从菜单中选择选项怎么样?因此,答案再次不适用于 chrome。但我仍然觉得右键单击有帮助。 *.com/questions/11428026/…
  • 我需要一个通用的解决方案,因为我不确定我的应用程序中有多少这样的链接。可能只是在浏览器级别配置它会帮助我为所有此类链接实现这一点。
  • 您是否尝试发送密钥Control + n,从而启动新窗口?然后在新窗口中启动链接?

标签: google-chrome selenium selenium-webdriver webdriver automated-tests


【解决方案1】:

我不是网页设计大师,但我可以建议以下场景:

// 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

此代码应允许您更改目标 Web 元素的 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 浏览器中没有任何标志/设置/功能(在新窗口而不是新标签页中打开链接)的情况下,我通过 WebDriver 使用了 Chrome 扩展程序。

    我为什么要这样做?

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

    我做了什么?

    1. 我使用了 chrome 扩展程序 New Tab New Window,它将所有新标签页打开到一个新窗口中。
    2. 使用扩展名Get CRX下载了此扩展名的CRX文件。
    3. 将 CRX 文件设置为 Chrome 的一项功能。

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

    所以上面会将所有新选项卡转换为新窗口。因此,每当驱动程序单击任何在新选项卡中进一步打开的链接时,都会在新窗口中打开。

    【讨论】: