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