python selenium - 当它找不到元素时需要很多时间 [英] python selenium - takes a lot of time when it does not find elements

查看:61
本文介绍了python selenium - 当它找不到元素时需要很多时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

my code scans a lot of internet pages with chromedriver and searches for the same element in each page with "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 秒,然后继续前进.

When it finds, one or multiple, it works fast and good. But, when the XPath doesn't exist it runs for 6-7 seconds and then moves on.

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

Can I limit the search for 1 second, And if it doesn't find in a second, just move on? Is there a way to do this?

推荐答案

尝试使用 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 列表,否则什么都不做

This should allow you to wait for 1 second until at least one element found and get the list of required WebElements or do nothing otherwise

这篇关于python selenium - 当它找不到元素时需要很多时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆