What is following-sibling in Selenium?


We can use the concept of following-sibling in xpath for identifying elements in Selenium. It identifies the siblings of the context node. The siblings should be located at the equal level of the existing node and should have the same parent.

Let us see an example of an element with ul tag having more than one child with li tag. Then let us try to locate the fifth li element (Effective Resume Writing) from the first li element with class attribute sreading.

Syntax

//li[@class='sreading']/following-sibling::li[4]

Here, we are locating the fifth child of ul tag, but we have provided li[4] since we are locating the fifth child from the first child element.

Example

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 FollowingSiblingXpath{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      //identify fifth child from first child
      WebElement n = driver.findElement
      (By.xpath("//li[@class='sreading']/following-sibling::li[4]"));
      String s = n.getText();
      System.out.println("Text is: " + s);
      driver.quit();
   }
}

Output

Updated on: 06-Apr-2021

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements