简体   繁体   English

如何使 Selenium python 代码更高效

[英]How can I make Selenium python code more efficient

I have a problem while doing some webscraping, it's I have 3 loops where I go through many links, but the problem is when it's get to the third link the code crashes.我在做一些网页抓取时遇到问题,我有 3 个循环,我通过许多链接 go,但问题是当它到达第三个链接时代码崩溃。 or How can I put some waits in my program without using the sleep function.或如何在不使用sleep function 的情况下在我的程序中放置一些等待。

Seems like what you want to do is wait for element to load.似乎您想要做的是等待元素加载。 For this selenium provides WebDriverWait() 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM