When do we use findElement() and findElements() in Selenium?

SeleniumAutomation TestingTesting Tools

The methods findElements and findElement are used to identify elements on a webpage. While findElement can pinpoint only one element, the findElements method yields a list of matching web elements.

The return type of findElements is a list whereas the return type of findElement is a WebElement. If there is no matching element on the page, an exception is thrown by the findElement method. In this scenario, an empty list id returned by the findElements method.

A good example of findElements method usage is counting the total number of links or accessing each of links by iterating through the links.


WebElement m = driver.findElement(By.linkText("Subject"));
List<WebElement> n =


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class FindElmntsvsFindElement{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      //identify an element with tagname
      WebElement e = driver.findElement(By.tagName("h2"));
      String str = e.getText();
      System.out.println("Get text on element: " + str);
      //identify elements with anchor image
      List<WebElement> m = driver.findElements(By.tagName("img"));
      //count images
      int s = m.size();
      System.out.println("Number of images: " + s);


Published on 06-Apr-2021 10:22:40