」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Python 中有效地暫停 Selenium WebDriver 執行?

如何在 Python 中有效地暫停 Selenium WebDriver 執行?

發佈於2024-12-26
瀏覽:114

How to Efficiently Pause Selenium WebDriver Execution in Python?

Selenium WebDriver 中的等待與條件語句

問題: 如何在 Python 中暫停 Selenium WebDriver 執行幾毫秒?

答案:

雖然time.sleep() 函數可用於暫停執行指定的秒數,在 Selenium WebDriver 自動化中一般不建議使用。

使用 Selenium 的 WebDriverWait

相反,Selenium 提供了 WebDriverWait 類別結合預期條件來驗證元素的狀態。以下是常見的預期條件:

  1. 定位元素的存在: 檢查 DOM 上是否存在元素。
  2. 定位元素的可見性: 檢查元素是否可見且高度和寬度是否大於 0。
  3. 要顯示的元素Clickable: 檢查元素是否可見、啟用和可互動。

範例:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10) # Timeout after 10 seconds

# Wait until an element is clickable
element = wait.until(EC.element_to_be_clickable((By.ID, "some_button")))
element.click()

此方法優於 time.sleep(),因為它可以避免不必要的等待並在繼續之前檢查元素的所需狀態,從而提高測試效率。

參考資料:

更多資訊參考:

  • WebDriver等等按預期工作:https://stackoverflow.com/ questions/37372143/webdriverwait-not-working-as-expected
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3