如何在 Python 的 Selenium 中切换到新窗口?
当打开多个窗口时,Selenium 可以切换到新窗口。在填写表单中的日期字段时可能会打开一个新窗口,或者点击链接、按钮或广告也会打开一个新标签页。
Selenium 使用 **current_window_handle** 和 **window_handles** 方法来处理新窗口。window_handles 方法包含所有已打开窗口的窗口句柄 ID。窗口 ID 句柄以 Set 数据结构的形式保存 [包含字符串数据类型]。
current_window_handle 方法用于存储当前活动窗口的窗口句柄 ID。最后,要切换到特定窗口,使用 **switch_to_window()** 方法。要切换到的窗口的句柄 ID 作为参数传递给该方法。
实现上述概念的步骤如下:
应用程序启动后,让我们首先使用 window_handles 方法将所有窗口句柄 ID 存储在 Set 数据结构中。
我们将遍历所有窗口句柄 ID,直到找到所需的窗口句柄 ID。
然后,让我们使用 current_window_handle 方法获取当前窗口句柄 ID。
然后使用 switch_to_window() 方法切换到该窗口。
示例
代码实现。
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.get("https://#/signup")
driver.find_element_by_link_text("Help").click()
#prints parent window title
print("Parent window title: " + driver.title)
#get current window handle
p = driver.current_window_handle
#get first child window
chwnd = driver.window_handles
for w in chwnd:
#switch focus to child window
if(w!=p):
driver.switch_to.window(w)
break
time.sleep(0.9)
print("Child window title: " + driver.title)
driver.quit()输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP