Search code examples
pythonseleniumif-statementwhile-loopnosuchelementexception

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

Solution

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