如何使用Python在Selenium中处理子窗口?
我们可以使用Selenium来处理子窗口或选项卡。在处理子窗口时,我们需要始终将浏览器焦点转移到子窗口,然后对其执行操作。
默认情况下,焦点始终位于第一个父窗口上。Selenium中有多种方法,如下所示——
current_window_handle
此方法获取当前窗口的句柄。
语法——
driver.current_window_handle
window_handles
此方法获取当前打开的所有窗口的句柄ID。
语法——
driver.window_handles w = driver.window_handles[2]
上例给出了本会话中打开的第二个窗口的句柄ID。
switch_to.window(args)
此方法将Selenium的焦点切换到参数中指定窗口名称。
语法——
driver.switch_to.window(childwindow)
上例将焦点切换到子窗口句柄。
示例
使用子窗口的代码实现。
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://the-internet.herokuapp.com/windows")
#to refresh the browser
driver.refresh()
driver.find_element_by_link_text("Click Here").click()
#prints the window handle in focus
print(driver.current_window_handle)
#to fetch the first child window handle
chwnd = driver.window_handles[1]
#to switch focus the first child window handle
driver.switch_to.window(chwnd)
print(driver.find_element_by_tag_name("h3").text)
#to close the browser
driver.quit()
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP