如何使用webdriver在chrome中打开新窗口而不是新选项卡?

Pri*_*har 5 selenium automated-tests google-chrome webdriver selenium-webdriver

为了自动化我的测试应用程序,我需要在新窗口中打开几个链接而不是tab.请记住,我没有明确地打开新标签中的链接,这是我的网络应用程序,它在点击链接后自动将用户放在新标签中.

我为什么要这样做?

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

到目前为止我做了什么?

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

And*_*son 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
Run Code Online (Sandbox Code Playgroud)

此代码应该允许您更改HTML目标 Web 元素的源代码,以强制其在新浏览器窗口中打开。

请注意,使用此代码元素在页面上的外观将发生变化,直到页面刷新

PS你没有提到你的编程语言,所以没有完整的实现......但是,这是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()
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

4310 次

最近记录:

7 年,2 月 前