Find Element and FindElements by XPath in Selenium

The findElement(By.xpath) method is used to identify an element which matches with the xpath locator passed as a parameter to this method. The findElements(By.xpath) method is used to identify a collection of elements which match with xpath locator passed as a parameter to that method.

The method findElement(By.xpath) returns a web element whereas the method findElements(By.xpath) returns a list of web elements. An exception is thrown by the method findElement(By.xpath) if there is no matching element. An empty list of elements is returned if there is no matching element obtained from the findElements(By.xpath) method.

Let us try to identify the number of children of the ul tag and also the first subelement of ul( li[1] having text Selected Reading).


List<WebElement> n =
driver.findElements(By.xpath("//ul[@class=' toc reading']/li"));
WebElement m =driver.findElement(By.xpath("//ul[@class=' toc reading']/li[1]"));


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class XpathFindElment{
   public static void main(String[] args) {
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      // identify elements with findElements xpath
      List p = driver.findElements(By.xpath("//ul[@class='toc reading']/li"));
      //count of list of matching elements
      int s = p.size();
      //identify element with xpath
      WebElement m = driver.findElement(By.xpath("//ul[@class='toc reading']/li[1]"));
      System.out.println("Element text is: "+ m.getText());



Updated on: 06-Apr-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started