Time.sleep() 在 ChromeDriver 上

Time.sleep() on ChromeDriver

我正在使用 ChromeDriver 使用 Python 进行一些网络抓取。 我的代码使用 browser.find_element_by_xpath 但我必须在 clicks/input 之间包含 time.sleep(3) 因为我需要等待网页加载才能执行下一行代码。

想知道是否有人知道执行此操作的最佳方法?也许一个功能可以在浏览器加载时立即自动执行下一行而不是等待任意秒数?

谢谢!

尝试使用 explicit wait 使用 expected_conditions,如下所示。

进口需要:

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 

让我知道这对你有用!