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 ofcountto get the number of elements. findElementsreturns an empty list if nothing is found—noNoSuchElementExceptionis thrown.- Use
equalsIgnoreCaseif the text case may vary. - Always quit the driver after execution to close the browser.
- Breaking the loop after clicking prevents
StaleElementReferenceException.