selenium-webdriver Error Handling in Automation using Selenium Python

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

WebDriverException is a base Selenium-WebDriver exception that could be used to catch all other Selenium-WebDriver exceptions

To be able to catch exception it should be imported first:

from selenium.common.exceptions import WebDriverException as WDE

and then:

try:
    element = driver.find_element_by_id('ID')
except WDE:
    print("Not able to find element")

In the same way you can import other more specific exceptions:

from selenium.common.exceptions import ElementNotVisibleException
from selenium.common.exceptions import NoAlertPresentException
...

If you want to extract exception message only:

from selenium.common.exceptions import UnexpectedAlertPresentException

try:
    driver.find_element_by_tag_name('a').click()
except UnexpectedAlertPresentException as e:
    print(e.__dict__["msg"])


Got any selenium-webdriver Question?