如何在Python中使用Selenium在由不同WebDriver打开的不同Chrome浏览器窗口之间切换? [英] How to switch between different chrome browser window opened by different WebDriver using selenium in Python?

查看:676
本文介绍了如何在Python中使用Selenium在由不同WebDriver打开的不同Chrome浏览器窗口之间切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I searched for this question,and I found an idea using driver.switch_to.window(),but it didn't work as expect:

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,然后

above code will first open a chrome window and go to google,then will open another chrome window and go to bing,then

driver1.switch_to.window(driver1.current_window_handle)

似乎没有用,显示bing的窗口仍显示在显示google的窗口上方. 有人知道吗?

seems didn't work,the window showing bing still shows on top of the window showing google. Anyone have any idea?I think

driver1.switch_to.window(driver1.current_window_handle)

可能有一些错误.

推荐答案

因为您分别使用两个 WebDriver 实例作为 driver1 driver2 打开 https://www.google.com (例如windowA)和

As you have used two WebDriver instances as driver1 and driver2 respectively to openthe urls https://www.google.com (e.g. windowA) and https://www.bing.com/ (e.g. windowB) it is worth to mention that the function switch_to.window() is a WebDriver method. So, driver1 can control only windowA and driver2 can control only windowB.

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

For Selenium to interact with any of the Browsing Window, Selenium needs focus. So to iterate among the different Browsing Windows you can shift the focus to the different Browsing Window using JavascriptExecutor as follows :

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

这篇关于如何在Python中使用Selenium在由不同WebDriver打开的不同Chrome浏览器窗口之间切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆