Python 中 Selenium 的顯式等待是什麼?


在使用 Selenium 時,可能會遇到這種情況:瀏覽器載入頁面後,網頁元素會在不同的時間間隔載入。

這種型別的情況會導致 Selenium 和頁面上的網頁元素之間出現同步問題。由於 DOM 中缺少該元素,因此無法識別元素。由於此原因,會丟擲 ElementNotVisibleException 等異常。

Selenium 中的等待概念克服了這個問題,並在元素識別和對其執行的操作之間提供延遲。顯式等待並非應用於所有元素,而是應用於頁面上的特定元素。它實際上是在執行測試用例的下一步之前必須滿足的條件。

顯式等待本質上也是動態的,這意味著只要需要,等待就會存在。因此,如果等待時間為 5 秒,並且在第 3 秒滿足了我們的給定條件,則無需在接下來的 2 秒內停止執行。

webdriverWait 類與 expected_conditions 一起用於建立顯式等待。預設情況下,webdriverWait 類可以每 500 毫秒呼叫一次 ExpectedCondition 以檢查條件是否滿足。

語法

w = WebDriverWait(driver, 7)
w.until(expected_conditions.presence_of_element_located((By.ID,
"Tutorialspoint")))

下面列出了顯式等待中常用的預期條件:

  • title_contains
  • visibility_of_element_located
  • presence_of_element_located
  • title_is
  • visibility_of
  • element_selection_state_to_be
  • presence_of_all_elements_located
  • element_located_to_be_selected
  • alert_is_present
  • element_located_selection_state_to_be
  • staleness_of
  • element_to_be_clickable
  • invisibility_of_element_located
  • frame_to_be_available_and_switch_to_it
  • text_to_be_present_in_element_value
  • text_to_be_present_in_element
  • element_to_be_selected

顯式等待比隱式等待更難實現,但它不會減慢執行速度,並且適用於頁面上的特定元素。

示例

使用顯式等待的程式碼實現。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
#setting implicit wait 10 seconds
driver.implicitly_wait(10)
# to maximize the browser window
driver.maximize_window()
driver.get("https://tutorialspoint.tw/tutor_connect/index.php")
#to refresh the browser
driver.refresh()
# identifying the link with the help of link text locator
driver.find_element_by_link_text("Search Students").click()
w.(expected_conditions.presence_of_element_located((By.
CSS_SELECTOR, "input[name = 'txtFilterLocation']")))
#to close the browser
driver.close()

更新於: 2020-07-28

2K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告