Search code examples
pythonandroidseleniumexceptionappium

Continue the script if an element is not found


There are at least 2 more questions on the platform but none of their answers helped me.

I just imported:

from selenium.common.exceptions import NoSuchElementException

then used:

if Newest_tab_button:
    print('element found')
else:
    print('not found')

or

try:
    wait = WebDriverWait(driver, 15)
    Newest_tab_button = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@text="NEWEST"]//ancestor::*[contains(@resource-id, "itemContainer")]')))
except NoSuchElementException:
    print('Element not found')

Nothing worked, still got the:

selenium.common.exceptions.TimeoutException: Message: 

Can anyone help me with that? Thanks in advance.


Solution

  • You can catch multiple Exceptions in the same except block or with multiple except block

    try:
        wait = WebDriverWait(driver, 15)
        Newest_tab_button = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@text="NEWEST"]//ancestor::*[contains(@resource-id, "itemContainer")]')))
    except TimeoutException as e:
        print("TimeoutException")
        
    except NoSuchElementException as e1:
        print("NoSuchElementException")
        
    except Exception as e3: # To catch an Exception other than the specified once.
        print(e3)
    

    Or you need to put all the Exceptions in a tuple:

    except (TimeoutException,NoSuchElementException): # This catches either TimeoutException or NoSuchElementException
        print("ERROR")