如何在Python中使用selenium在不同Web驱动程序打开的不同chrome浏览器窗口之间切换?

如何在Python中使用selenium在不同Web驱动程序打开的不同chrome浏览器窗口之间切换?,python,selenium,selenium-webdriver,webdriver,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")

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

可能有一些错误。

我相信您在驱动程序中对“窗口”有不同的概念。请切换到.window()。在chrome浏览器中,它的意思是“选项卡”。它不是另一个chrome浏览器或浏览器窗口,就像您在代码中尝试做的那样

如果将_切换到.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
由于您分别使用了driver1driver2两个WebDriver实例来打开URL(例如windowA)和(例如windowB),因此值得一提的是,该函数是一种WebDriver方法。因此,driver1只能控制windowA,driver2只能控制windowB

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

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

谢谢。我误解了“切换到窗口”的意思,它会在同一个webdriver中的选项卡之间切换。但我真正理解的是在不同的webdriver窗口之间切换,你有什么建议吗?