[英]Time.sleep() on ChromeDriver
我正在使用 ChromeDriver 使用 Python 進行一些網絡抓取。 我的代碼使用browser.find_element_by_xpath
但我必須在點擊/輸入之間包含time.sleep(3)
因為我需要等待網頁加載才能執行下一行代碼。
想知道是否有人知道這樣做的最佳方法? 也許是一種可以在瀏覽器加載時立即自動執行下一行而不是等待任意秒數的功能?
謝謝!
嘗試使用expected_conditions
進行explicit wait
,如下所示。
進口需要:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
然后你可以在交互之前等待元素出現。
# waiting for max of 30 seconds, if element present before that it will go on to the next line.
ele = WebDriverWait(driver,30).until(EC.presence_of_element_located((By.XPATH,"xpath_goes_here")))
ele.click() # or what ever the operation like .send_keys()
這樣,應用程序將動態等待元素出現。 如果需要,請根據您的應用程序將時間從 30 秒更新。
您也可以在檢查元素存在時使用不同的位置策略,例如: By.CSS_SELECTOR/By.ID/By.CLASS_NAME
我已經為這種情況使用了一個函數,為腳本增加了健壯性。 例如通過 xpath 查找元素:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions as EC
def findXpath(xpath,driver):
actionDone = False
count = 0
while not actionDone:
if count == 3:
raise Exception("Cannot found element %s after retrying 3 times.\n"%xpath)
break
try:
element = WebDriverWait(driver, waitTime).until(
EC.presence_of_element_located((By.XPATH, xpath)))
actionDone = True
except:
count += 1
sleep(random.randint(1,5)*0.1)
return element
讓我知道這對你有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.