Home > other >  Continue the script if an element is not found
Continue the script if an element is not found

Time:10-14

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.

CodePudding user response:

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

CodePudding user response:

In the second method, you're only catching NoSuchElementException but the issue is that your script is timing out and you're getting a TimeoutException, you just need to catch that too to continue the script

from selenium.common.exceptions import NoSuchElementException, TimeoutException

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, TimeoutException) as error:
    print(error)
# Continue with the script
  • Related