Python 的 Selenium 中有哪些不同的等待方式?


在使用 Selenium 時,可能會出現瀏覽器頁面載入完成後,網頁元素以不同的時間間隔載入的情況。

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

Selenium 中的等待機制克服了這個問題,並在元素識別和對其執行操作之間設定了延遲。Selenium web driver 主要支援兩種型別的等待:

  • 隱式等待

這是應用於頁面上所有元素的全域性等待。等待時間作為引數提供給方法。例如,如果等待時間為 5 秒,則在丟擲超時異常之前,它將等待這段時間。

隱式等待是動態等待,這意味著如果元素在第三秒可用,那麼我們將繼續執行測試用例的下一步,而不是等待全部五秒。

隱式等待會通知 web driver 輪詢特定時間段。一旦確定了這段時間,它將持續整個 driver 會話。隱式等待的預設時間為 0。

語法

driver.implicitly_wait(8)
  • 顯式等待

顯式等待並非應用於所有元素,而是應用於頁面上的特定元素。它實際上是一個必須滿足的條件,然後才能繼續執行測試用例的下一步。

顯式等待也是動態的,這意味著等待將持續到必要時為止。因此,如果等待時間為五秒,而我們的給定條件在第三秒滿足,則無需在接下來的兩秒鐘內停止執行。

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

語法

w = WebDriverWait(driver, 6)
w.until(expected_conditions.presence_of_element_located((By.CLASS_NA
ME, "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

示例

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

from selenium import webdriver
#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()
#get method to launch the URL
driver.get("https://tutorialspoint.tw/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of id
driver.find_element_by_id("gsc-i-id1").send_keys("Selenium")
#to close the browser
driver.close()

示例

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

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 Tutors").click()
w.(expected_conditions.presence_of_element_located((By.
CSS_SELECTOR, "input#txtFilterLocation")))
#to close the browser
driver.close()

更新於:2020年7月28日

412 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.