1

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

1 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.