简体   繁体   中英

Python Selenium How to handle NoSuchElementException from while loop/if else statement

I'm trying to write a while loop where if an element isn't found it does certain tasks, however when the element is not found, it throws an error NoSuchElementException as if there is no element, instead of going to the 'else' statement.

elem = driver.find_element_by_id('add-to-bag')

while True:
    if elem.is_displayed():
        False
    else:
        driver.delete_all_cookies()
        driver.refresh()
        sleep(randint(5, 10))

As per your code block when you mention if an element is found it does certain tasks, however when the element is not found, it throws an error code is perfect .

Explanation

The code to find the element is just before the while/if block started. So when your find_element_by_id('add-to-bag') fails instead of returning an element it is returning NoSuchElementException which you havn't handled.

Solution

A simple solution would be to induce a try-except block for find_element_by_id('add-to-bag') as follows :

try :
    elem = driver.find_element_by_id('add-to-bag')
    if elem.is_displayed():
        //implement your logic

except NoSuchElementException :
    driver.delete_all_cookies()
    driver.refresh()
    sleep(randint(5, 10))

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