Skip to main content
 首页 » 编程设计

python selenium之找不到元素时会花费很多时间

2025年02月15日8think

我的代码使用 chromedriver 扫描了很多互联网页面,并使用“find_elements_by_xpath”在每个页面中搜索相同的元素

Lines = driver.find_elements_by_xpath( 
                    '//*[@id="top"]/div[contains(@style, "display: block;")]/' 
                    'div[contains(@style, "display: block;")]//tbody//a[contains(@title, "Line")]') 

当它找到一个或多个时,它会快速有效地工作。但是,当 XPath 不存在时,它会运行 6-7 秒,然后继续。

我可以将搜索限制为 1 秒,如果一秒内找不到,就继续前进吗?有办法做到这一点吗?

请您参考如下方法:

尝试使用ExplicitWait如下:

from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait as wait 
from selenium.common.exceptions import TimeoutException 
 
try: 
    Lines = wait(driver, 1).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="top"]/div[contains(@style, "display: block;")]/' 
                'div[contains(@style, "display: block;")]//tbody//a[contains(@title, "Line")]'))) 
except TimeoutException: 
    pass 

这应该允许您等待 1 秒,直到找到至少一个元素并获取所需 WebElements 的列表,否则什么都不做