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()

更新於:2020年7月29日

906 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告