Software Development

Checking if an Element Exists Using Selenium WebDriver

When automating tests with Selenium WebDriver, it’s crucial to ensure that specific elements exist on the page before performing actions on them. There are several methods in Selenium WebDriver to check if an element exists. Let us delve into understanding how to use Selenium WebDriver to check if an element exists.

1. Overview

In Selenium, the most common methods to locate elements on a web page are findElement() and findElements(). While both methods serve the purpose of finding web elements, they handle non-existing elements differently:

  • findElement(): This method throws a NoSuchElementException if the element is not found.
  • findElements(): This method returns an empty list if no matching elements are found.

2. Using the findElements() Method

The findElements() method returns a list of WebElements. If no elements are found, it simply returns an empty list. This is the safest way to check if an element exists without handling exceptions.

2.1 Code Example

Let’s examine the code below.

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class CheckElementWithFindElements {
  public static void main(String[] args) {
    // Set the path to the WebDriver executable
    System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

    // Initialize WebDriver
    WebDriver driver = new ChromeDriver();

    // Open a website
    driver.get("https://example.com");

    // Use findElements to check if an element exists
    List <WebElement> elements = driver.findElements(By.id("non-existent-id"));

    // Check if the list is empty
    if (elements.isEmpty()) {
      System.out.println("An element does not exist.");
    } else {
      System.out.println("Element exists.");
    }

    // Close the browser
    driver.quit();
  }
}

The code defines a:

  • The findElements() method returns a list of elements found by the specified locator (By.id("non-existent-id")).
  • If the list is empty, it means no matching elements were found on the page.
  • The code handles the situation without throwing an exception if the element is not found.

When we run the above code, the following output will be shown on the IDE console:

An element does not exist.

If the elements exist under a specified locator the following output will be shown on the IDE console:

Elements exists.

3. Using the findElement() Method

The findElement() method returns a single WebElement. If the element is not found, it throws a NoSuchElementException. This method is useful when you expect the element to be present and want the test to fail if it’s not found.

3.1 Code Example

Let’s examine the code below.

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class CheckElementWithFindElement {
  public static void main(String[] args) {
    // Set the path to the WebDriver executable
    System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

    // Initialize WebDriver
    WebDriver driver = new ChromeDriver();

    // Open a website
    driver.get("https://example.com");

    try {
      // Use findElement to check if an element exists
      WebElement element = driver.findElement(By.id("non-existent-id"));
      System.out.println("Element exists.");
    } catch (NoSuchElementException e) {
      System.out.println("An element does not exist.");
    }

    // Close the browser
    driver.quit();
  }
}

The code defines a:

  • The findElement() method searches for a single element on the page.
  • If the element is not found, it throws a NoSuchElementException, which we handle using a try-catch block.
  • This method is ideal when you want to immediately know if an element cannot be found, and you prefer exceptions to handle such cases.

When we run the above code, the following output will be shown on the IDE console:

An element does not exist.

4. Conclusion

Both findElement() and findElements() methods are useful when checking for element existence in Selenium WebDriver. If you want to avoid exceptions and safely check if an element exists, findElements() is the better choice. On the other hand, if you expect the element to be present and want the test to fail if it’s not, findElement() is more appropriate. Use the appropriate method based on your needs and how you want to handle missing elements in your test automation.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button