How to select specified node within Xpath node sets by index with Selenium?


We can select specific nodes within xpath node sets by index with Selenium webdriver. We can mention a specific node with the help of its index number enclosed in [].

Let us have a look at the below html code for an element having children. The element with tagname ul has multiple child elements with tagname li. If we want to identify the second child of the parent having text as Software Quality management the xpath expression with node index shall be //ul[@class='list']li[2].

The xpath expression to identify the second child of the parent element ul can also be created with the help of position() function in xpath. To pinpoint the second element we have to append position()=2 to the xpath. So the complete xpath expression shall be //ul/[@class='list']/li[position()=2].

Example

Code Implementation with xpath having index

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;
public class ElementIndex{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/tutorials_writing.htm");
      // identify element with xpath having index
      WebElement t = driver.findElement(By.xpath("//ul[@class='list']/li[2]"));
      //getText to get element text
      System.out.println("The element is: " + t.getText());
      driver.close();
   }
}

Code Implementation with xpath having position().

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;
public class ElementPosition{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/tutorials_writing.htm");
      // identify element with xpath having position()
      WebElement t = driver.findElement(By.xpath("//ul[@class='list']/li[position()=2]"));
      //getText to get element text
      System.out.println("The element is: " + t.getText());
      driver.close();
   }
}

Output

Updated on: 26-Oct-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements