Python 的 Selenium 中,`current_window_handle` 和 `window_handles` 方法有什么区别?
Selenium 中 `current_window_handle` 和 `window_handles` 方法之间存在差异。两者都是用于处理多个窗口的方法,区别如下:
`current_window_handle`
此方法获取当前窗口的句柄。因此,它处理当前焦点所在的窗口。它返回窗口句柄 ID,其值为字符串。
**语法** −
driver.current_window_handle
`window_handles`
此方法获取当前所有打开窗口的句柄 ID。窗口句柄 ID 的集合以集合数据结构的形式返回。
**语法** −
driver.window_handles w = driver.window_handles[2]
以上代码给出当前会话中打开的第二个窗口的句柄 ID。
示例
使用 `current_window_handle` 的代码实现
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 close the browser driver.quit()
使用 `window_handles` 的代码实现。
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 all handle ids of opened windows chwnd = driver.window_handles; # count the number of open windows in console print("Total Windows : "+chwnd.size()); #to close the browser driver.quit()
广告