繁体   English   中英

如何在Python中使用Selenium在由不同WebDriver打开的不同Chrome浏览器窗口之间切换?

[英]How to switch between different chrome browser window opened by different WebDriver using selenium in Python?

我搜索了这个问题,并使用driver.switch_to.window()找到了一个主意,但它没有按预期工作:

from selenium import webdriver

driver1=webdriver.Chrome("D:\Python\Files\chromedriver.exe")
driver1.get('https://www.google.com')


driver2=webdriver.Chrome("D:\Python\Files\chromedriver.exe")
driver2.get('https://www.bing.com/')

driver1.switch_to.window(driver1.current_window_handle)

上面的代码将首先打开一个chrome窗口并转到google,然后将打开另一个chrome窗口并转到bing,然后

driver1.switch_to.window(driver1.current_window_handle)

似乎没有用,显示bing的窗口仍显示在显示google的窗口上方。 有人有什么主意吗?

driver1.switch_to.window(driver1.current_window_handle)

可能有一些错误。

正如你已经使用了两个实例的webdriver作为驱动1和分别驱动2至openthe网址https://www.google.com (如窗口A)和https://www.bing.com/ (如窗口B)值得一提的是, switch_to.window()函数是一个WebDriver方法。 因此, 驱动1只能控制窗口A驱动2只能控制窗口B。

为了使Selenium与任何浏览窗口进行交互, Selenium需要重点关注 因此,不同的浏览窗你们中间迭代可以将重点转移到使用JavascriptExecutor如下不同的浏览窗口

((JavascriptExecutor) driver1).executeScript("window.focus();");
((JavascriptExecutor) driver2).executeScript("window.focus();");

我相信您在driver.switch_to.window()中有一个不同的“窗口”概念。 在chrome浏览器中,它的意思是“标签”。 它不是另一个chrome浏览器或浏览器窗口,就像您要在代码中尝试执行的操作一样。

如果switch_to.window()是您真正想要的,我将举一个如何使用它的示例:

driver=webdriver.Chrome("D:\Python\Files\chromedriver.exe")
driver.get('https://www.google.com')
# open a new tab with js
driver.execute_script("window.open('https://www.bing.com')")
driver.switch_to.window(driver.window_handles[-1])
# now your driver is pointed to the "tab" you just opened

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM