python - 如何在Python中使用selenium在不同WebDriver打开的不同chrome浏览器窗口之间切换?

标签 python selenium selenium-webdriver webdriver

我搜索了这个问题,发现了一个使用 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)

可能有一些BUG。

最佳答案

由于您已使用两个WebDriver实例分别作为driver1driver2来打开网址https://www.google.com (例如窗口A)和https://www.bing.com/ (例如 windowB)值得一提的是函数 switch_to.window()是一个WebDriver方法。因此,driver1 只能控制windowAdriver2 只能控制windowB

要使Selenium与任何浏览窗口交互,Selenium需要焦点。因此,要在不同的浏览窗口之间进行迭代,您可以使用JavascriptExecutor将焦点转移到不同的浏览窗口,如下所示:

  • Python:

    driver1.execute_script("window.focus();")
    driver2.execute_script("window.focus();")
    
  • Java:

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

关于python - 如何在Python中使用selenium在不同WebDriver打开的不同chrome浏览器窗口之间切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900393/

相关文章:

python - 使用 dxl 将 DOORS 对象导出到 csv 文件不会写入所有对象?

python - 编写一个函数 intreverse(n),它以正整数 n 作为输入,并返回通过反转 n 中的数字而获得的整数

java - driver.findby Xpath 中的标记存在语法错误

java - Selenium 使用 JavascriptExecutor 等待页面完全加载

python - 打开多个 CSV 文件

python - 从 Cherrypy 服务器捕获退出信号

testing - 运行在 Selenium IDE 中开发的多个测试

c# - 从 iFrame 切换到父框架并使用 Selenium Webdriver 在父框架中查找元素。 C#

java - Xpath 2.0 函数无法在使用 Saxon 的 Java 中工作

python - 如何设置python Selenium 3.8.0的 'driver.get'超时?