Find elements using Selenium WebDriver?

We can find elements using Selenium webdriver with the help of the findElements method. This can be applied to the locators like id, class, name, link text, partial link text, css, xpath and tagname.

The findElements method returns a list of elements which match with the locator (with the By object) passed as a parameter to the method. To count the number of elements returned by the list, the method size is used. If there are no matching elements, an empty list is returned.

The below image shows the list of methods available with findElements.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class FindElmnts{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      //identify elements with anchor tagname
      List e = driver.findElements(By.tagName("a"));
      //count matching elements with size
      int s = e.size();
      System.out.println("Number of matching elements: " + s);