How to handle exceptions in Selenium?

Handling exceptions in Selenium is a crucial skill for web scraping or automation testing. Selenium provides several exceptions that can be used to handle different situations during test execution.

In Python and JavaScript, you can handle exceptions using the try/except and try/catch blocks respectively.

Python

In Python, you can use the try/except block to handle exceptions. Here is an example:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox()

try:
    element = driver.find_element_by_id("my-id")
except NoSuchElementException:
    print("Element not found")
finally:
    driver.quit()

In this example, we try to find an element by its ID. If the element is not found, a NoSuchElementException is raised, and we handle it by printing a message and then quitting the driver.

JavaScript

In JavaScript, you can use the try/catch block to handle exceptions. Here is an example using WebDriverJS:

const {Builder, By, Key, until} = require('selenium-webdriver');

let driver = new Builder().forBrowser('firefox').build();

try {
    await driver.get('http://www.google.com');
    let element = await driver.findElement(By.name('q'));
    await element.sendKeys('webdriver', Key.RETURN);
    await driver.wait(until.titleIs('webdriver - Google Search'), 1000);
} catch (error) {
    console.log('An error occurred: ', error);
} finally {
    await driver.quit();
}

In this example, we try to open a webpage and perform a search. If anything goes wrong (like the page not loading or the element not being found), an error is thrown and we handle it by logging the error and then quitting the driver.

Common Exceptions

Here are some common exceptions you might encounter when using Selenium:

  • NoSuchElementException: Thrown when an element with a certain attribute is not found.
  • TimeoutException: Thrown when a command does not complete in enough time.
  • WebDriverException: This class is the base class for all exceptions thrown by the WebDriver implementation in Python.
  • ElementNotVisibleException: Thrown when an element is present in the DOM but not visible, so the operation cannot be completed.
  • InvalidSelectorException: Thrown when the selector used to find an element does not return a WebElement.

Remember that handling exceptions correctly is important for the stability of your code. It allows your code to continue executing even when an exception occurs.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon