如何使用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()