exceptions-in-selenium

Selenium Exception Handling Guide

Introduction:

Selenium is a powerful tool, however, being a complex software, it has its difficulties. Selenium exceptions can be painful and time-consuming to debug but with the right knowledge & strategy approach you would become an expert in handling them. In this Blog, we will classify the popular Selenium exceptions and discuss from where these can occur to how you can handle them.

What are Selenium Exceptions?

Selenium exceptions are actually the errors occurred when your test script tries to perform some operation over a web application using Selenium WebDriver. The WebDriver, the browser or the application might throw these exceptions in any case. They can be as basic as a timeout or as serious as a WebDriver crash.

Common Selenium Exceptions:

Here is a list of common Selenium exceptions and how you can handle them:

1. NoSuchElementException
  • Exception Thrown – when the WebDriver can’t find an element on the page.
Handling:
  • Use a more robust locator (e.g., XPath, CSS selector) instead of ID or Name.
  • Verify that the element is present on the page before interacting with it.
  • Use ‘WebDriverWait’ to wait for the element to be visible or clickable.
  • Check if the element is hidden or not displayed.
element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, "//div[@class='example']"))
)
2. TimeoutException
  • Exception Thrown – when the WebDriver takes too long to perform an action.
Handling:
  • Increase the timeout value using ‘WebDriverWait’ or ‘ImplicitWait’.
  • Verify that the action is taking too long to complete.
  • Check if the application is slow or unresponsive.
  • Use ‘ExpectedConditions’ to wait for a specific condition to be met.
try:
    element = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//div[@class='example']"))
    )
except TimeoutException:
    print("Element not found within the timeout.")
3. StaleElementReferenceException
  • Exception Thrown – when the WebDriver tries to interact with an element that’s no longer present on the page.
Handling:
  • Use ‘WebDriverWait’ to wait for the element to be stale before interacting with it.
  • Verify that the element is still present on the page before interacting with it.
  • Use a more robust locator to identify the element.
  • Check if the page has changed or reloaded.
try:
    element.click()
except StaleElementReferenceException:
    element = driver.find_element(By.XPATH, "//div[@class='example']")
    element.click()
4. WebDriverException
  • Exception Thrown – when the browser crashes or becomes unresponsive.
Handling:
  • Restart the browser or WebDriver instance.
  • Check if the browser is outdated or incompatible with the WebDriver version.
  • Verify that the system resources are sufficient to run the browser.
  • Use a more stable browser or WebDriver instance.
try:
    driver.get("https://example.com")
except WebDriverException:
    print("WebDriverException occurred. Restarting the browser.")
    driver.quit()  # Close the browser and quit the WebDriver
    driver = webdriver.Chrome()
5. ElementNotVisibleException
  • Exception Thrown – when the WebDriver tries to interact with an element that’s not visible on the page.
Handling:
  • Use ‘WebDriverWait’ to wait for the element to be visible before interacting with it.
  • Verify that the element is visible on the page before interacting with it.
  • Check if the element is hidden or not displayed.
  • Use ‘ExpectedConditions’ to wait for the element to be visible.
 # Wait Until the element is visible
element = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.XPATH, "//div[@class='example']"))
    )
    element.click()
6. ElementNotSelectableException
  • Exception Thrown – when the WebDriver tries to interact with an element that’s not selectable.
Handling:
  • Verify that the element is selectable before interacting with it.
  • Check if the element is disabled or not enabled.
  • Use ‘WebDriverWait’ to wait for the element to be selectable before interacting with
    it.
  • Use ‘ExpectedConditions’ to wait for the element to be selectable.
if element.is_enabled() and element.is_displayed():
    element.click()
7. NoSuchWindowException
  • Exception Thrown – when the WebDriver can’t find a window or tab.
Handling:
  • Verify that the window or tab is present before switching to it.
  • Use ‘WebDriver’ to switch to the correct window or tab.
  • Check if the window or tab has been closed or is no longer present.
Window = driver.window_handles
driver.switch_to.window(window[-1])  # Switch to the last window
8. NoSuchFrameException
  • Exception Thrown – when the WebDriver can’t find a frame.
Handling:
  • Verify that the frame is present before switching to it.
  • Use ‘WebDriver’ to switch to the correct frame.
  • Check if the frame has been removed or is no longer present. 
WebDriverwait(driver, 10).until(
             EC.frame_to_be available_and_switch_to_it("frame_name")
9. UnexpectedTagNameException
  • Exception Thrown – when the WebDriver encounters an unexpected tag name.
Handling:
  • Verify that the element has the correct tag name.
  • Check if the element has been modified or changed.
  • Use a more robust locator to identify the element.
if element.tag_name == "select":
    select = select(element)
    select.select_by_visible_text("option")
10. InvalidSelectorException
  • Exception Thrown – when the WebDriver encounters an invalid selector.
Handling:
  • Verify that the selector is correct and valid.
  • Check if the selector has been modified or changed.
  • Use a more robust locator to identify the element.
try:
    element = driver.find_element(By.XPATH, "Invalid_xpath")
except InvalidSelectorException:
    print("Invalid selector used.")
11. ElementClickInterceptedException-
  • Exception Thrown – when the WebDriver tries to click on an element that is intercepted by another element.
Handling:
  • Verify that the element is not intercepted by another element.
  • Check if the element has been overlapped by another element.

Use ‘Actions’ class to move the mouse to the element and then click on it.

from selenium.webdriver.common.action_chains import ActionChains

element = driver.find_element(By.ID, "my_element")
ActionChains(driver).move_to_element(element).click().perform()
12. NoAlertOpenException
  • Exception Thrown – when the WebDriver tries to switch to an alert that is not open.
Handling:
  • Verify that the alert is open before switching to it.
  • Check if the alert has been closed or is no longer present.
  • Use ‘Alert’ interface to switch to the alert.
try: 
   WebDriverWait(driver, 10).until(EC.alert_is_present())
    alert = driver.switch_to.alert
    alert.accept()
except NoAlertPresentException:
    print("No alert present.")
Some Ways to Handle Selenium Exceptions:

Here are some ways to help you handle exceptions in Selenium:

  •  Use Try-Catch Blocks: Wrap your test code in try-catch blocks to catch exceptions as they occur.
  • Use Waits: Implement waits to give the WebDriver enough time to find elements or perform actions.
  • Use Robust Locators: Use robust locators that can withstand changes to the application.
  • Update Your WebDriver: Keep your WebDriver up-to-date to ensure you have the latest bug fixes and features.
  • Monitor Your Tests: Monitor your tests regularly to identify patterns of exceptions.
  • Use Selenium Grid: Use Selenium Grid to distribute your tests across multiple machines, reducing the likelihood of exceptions.
  • Use TestNG or JUnit: Use testing frameworks like TestNG or JUnit to handle exceptions and provide meaningful error messages.
Best Practices for Handling Selenium Exceptions:
  • Log Exceptions: Log exceptions to help you identify the root cause of the issue.
  •  Provide Meaningful Error Messages: Provide meaningful error messages to help you understand what went wrong.
  • Rerun Failed Tests: Rerun failed tests to ensure that the issue is not intermittent.
  • Test in Different Environments: Test in different environments to ensure that the issue is not specific to a particular setup.
Conclusion:

Exception handling is a crucial aspect of writing reliable Selenium tests and Selenium exceptions are a natural part of the testing process, but with the right knowledge and strategies, you can handle them easily. By understanding when exceptions occur and how to handle them, you can write more robust tests that provide accurate results. Proper exception handling not only ensures that your tests failed in a controlled way but also provides meaningful feedback, making debugging easier and faster. Applying these practices will improve the stability and maintenance of your test automation setup.

Write A Comment