简体   繁体   English

用于尽快检查硒中是否存在元素的Python代码

[英]Python code to check if element exists in selenium as fast as possible

I'm new to Python and I am trying to make a program code to check if element ID exist or present in the page as fast as possible and if it does not exist it keeps refreshing the page untill it exist..我是 Python 的新手,我正在尝试制作一个程序代码来检查元素 ID 是否存在或尽快出现在页面中,如果它不存在,它会不断刷新页面直到它存在..

I tried driver.find_element by ID with try and except and it takes about six seconds to execute the process I need a faster method to check if the element exist我用 try 和 except 按 ID 尝试了 driver.find_element ,执行该过程大约需要六秒钟我需要一种更快的方法来检查元素是否存在

my past code was:我过去的代码是:

while true:
        try:
            a = driver.find_element_by_id('ID')
            break
        except NoSuchElementException:
            driver.refresh()

it works fine but I was wondering if there is a way to make the process faster.. Thank you,它工作正常,但我想知道是否有办法让这个过程更快..谢谢,

That depends how the website makes the element to appear.这取决于网站如何使元素出现。

If it is a relatively static website, that means the element can only appear after a refresh, then your code is the fastest code possible.如果它是一个相对静态的网站,这意味着该元素只能在刷新后出现,那么您的代码是最快的代码。

If the element is created using javascript, that means it will appear on the website even without a refresh, then this might be faster:如果该元素是使用 javascript 创建的,这意味着即使不刷新它也会出现在网站上,那么这可能会更快:

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, 'ID'))
)

it checks for element every 500 ms until it is found or timeout after 10 seconds.它每 500 毫秒检查一次元素,直到找到它或在 10 秒后超时。

read here for more information: https://selenium-python.readthedocs.io/waits.html阅读此处了解更多信息: https ://selenium-python.readthedocs.io/waits.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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