[英]How can I make Selenium python code more efficient
我在做一些網頁抓取時遇到問題,我有 3 個循環,我通過許多鏈接 go,但問題是當它到達第三個鏈接時代碼崩潰。 或如何在不使用sleep
function 的情況下在我的程序中放置一些等待。
似乎您想要做的是等待元素加載。 為此 selenium 提供了WebDriverWait()
function。
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('url')
timeout = 5
try:
element_present = EC.presence_of_element_located((By.ID, 'element_id'))
WebDriverWait(driver, timeout).until(element_to_be_present)
except TimeoutException:
print("Timed out waiting for page to load")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.