简体   繁体   中英

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..

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

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:

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.

read here for more information: https://selenium-python.readthedocs.io/waits.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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