How to Handle findElements in Selenium with Java Using a List

Handling multiple elements in Selenium is often done by assigning the results of findElements to a List. Once assigned, we can get the total number of matching elements using the size() method.

One important difference between findElement and findElements is that findElements does not throw an exception if no elements are found—it simply returns an empty list. This means your Selenium test won’t fail automatically, so you should explicitly check the list size before performing actions.

Below is an example where we retrieve all <a> tags from a web page, then click the one whose link text is "Your Account":

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

public class SampleTest {

WebDriver driver;

@Test
public void handleElements() {
    driver = new ChromeDriver();
    driver.get("https://www.amazon.com");

    // Find all links on the page
    List<WebElement> links = driver.findElements(By.tagName("a"));
    System.out.println("Total links found: " + links.size());

    // Iterate and click the link with text "Your Account"
    for (WebElement link : links) {
        if (link.getText().equalsIgnoreCase("Your Account")) {
            link.click();
            break; // Stop loop after clicking
        }
    }

    driver.quit();
}

}

Key Points:

  • Use size() instead of count to get the number of elements.
  • findElements returns an empty list if nothing is found—no NoSuchElementException is thrown.
  • Use equalsIgnoreCase if the text case may vary.
  • Always quit the driver after execution to close the browser.
  • Breaking the loop after clicking prevents StaleElementReferenceException.
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x