findElements(By by)

Estimated reading: 5 minutes 22 views

Overview

The findElements(By by) method in Selenium WebDriver is used to locate multiple web elements on a web page that match a specified locator strategy. Unlike findElement(), which returns only the first matching element, findElements() returns a list of WebElement objects that correspond to all elements matching the given locator. If no elements are found, it returns an empty list instead of throwing an exception.

This method is helpful when you need to interact with a set of elements on a page, such as retrieving a list of links, checkboxes, buttons, or any other repeating elements within the web page.

Syntax

				
					List<WebElement> elements = driver.findElements(By.xpath("//div[@class='product']"));
				
			
  • By.xpath("//div[@class='product']"): Specifies the locator strategy (XPath) and the criteria to find the elements.
  • The method returns a List<WebElement>, which contains all the matching elements. You can then interact with these elements or retrieve specific ones by index.

Usage

The findElements() method is useful when you need to interact with multiple elements. Here are some common use cases:

  1. Locating Multiple Elements by XPath: If you want to select all product names from a list of products displayed on a page, you can use this method to fetch them all at once.

				
					List<WebElement> products = driver.findElements(By.xpath("//div[@class='product-name']"));
for (WebElement product : products) {
    System.out.println(product.getText()); // Print the name of each product
}
				
			

2. Locating Multiple Links: To find and interact with all the links on a webpage, findElements() can be used to retrieve all <a> tags.

				
					List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
    System.out.println(link.getAttribute("href")); // Print the href attribute of each link
}
				
			

3. Locating Checkboxes: If you have a form with multiple checkboxes, you can retrieve all of them and then select or deselect specific ones.

				
					List<WebElement> checkboxes = driver.findElements(By.cssSelector(".checkbox-class"));
for (WebElement checkbox : checkboxes) {
    if (!checkbox.isSelected()) {
        checkbox.click(); // Select checkboxes that are not already selected
    }
}
				
			

4. Finding Elements in a Table: You can use findElements() to find rows or cells in an HTML table.

				
					List<WebElement> rows = driver.findElements(By.xpath("//table[@id='example']//tr"));
for (WebElement row : rows) {
    System.out.println(row.getText()); // Print text of each row in the table
}
				
			

Example

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

import java.util.List;

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

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

        // Navigate to a page
        driver.get("https://www.example.com");

        // Find multiple product names using XPath
        List<WebElement> products = driver.findElements(By.xpath("//div[@class='product-name']"));
        for (WebElement product : products) {
            System.out.println(product.getText()); // Print the name of each product
        }

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

Importance

The findElements(By by) method is important for several reasons:

  • Handling Multiple Elements: It allows you to handle scenarios where multiple elements match a given locator, such as fetching a list of items or links.
  • Efficient Interaction with Repeated Elements: When working with multiple identical elements on a page, findElements() allows you to fetch and interact with all of them at once, which can be more efficient than querying each element individually.
  • Useful for Loops: This method is commonly used in loops to iterate over multiple elements and perform actions, such as selecting checkboxes, validating text, or clicking on a series of buttons.

Limitations

  • Empty List Returned: If no elements match the locator, findElements() returns an empty list, rather than throwing an exception. This may require you to add extra logic to check if the list is empty before proceeding with further actions.
  • Performance Considerations: Retrieving and interacting with a large number of elements could impact performance. You should ensure that you use efficient locators (e.g., By.id or By.className) when dealing with a large set of elements.
  • No Element Interaction Directly: Since findElements() returns a list, you need to iterate through the list to interact with each element individually. This is different from findElement(), which directly returns a single element for immediate interaction.

Conclusion

The findElements(By by) method in Selenium WebDriver is a powerful tool for finding multiple elements on a web page. It enables efficient interactions with groups of elements, such as fetching a list of links, product names, or form controls. By returning a list of matching elements, it allows you to perform bulk actions, making it ideal for scenarios where multiple identical elements are present on the page.

Key Features

  • Returns a List of Elements: Unlike findElement(), which returns only the first matching element, findElements() returns a list of all matching elements.
  • Works with Various Locators: Supports different locator strategies like id, name, xpath, and cssSelector for finding multiple elements.
  • Empty List on No Match: Returns an empty list if no matching elements are found, preventing exceptions and offering more control over how to handle non-matches.
  • Useful for Bulk Actions: Ideal for iterating over multiple elements (e.g., clicking, sending text, or validating multiple items) at once.

Leave a Comment

Share this Doc

findElements(By by)

Or copy link

CONTENTS