How to get the following-sibling element for a table type of structure in Selenium?


We can get the following-sibling element for a table type of structure in Selenium webdriver. A following-sibling is used to determine the siblings of the context node.

Also, these siblings should be present at the same hierarchy of the current node and share the same parent. Let us take an instance of a table with table tag having multiple children with tag tr.

Then let us try to identify the elements in the third row highlighted on the below image from the first row which contains the table headers.

Syntax

//table[@id='table1']/tbody/tr[1]/following-sibling::tr[2]/td

Here, we are locating the third row in the table, but we have provided followingsibling::tr[2] since we are locating the third row from the first row.

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 FollowingSiblingTable{
   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://sqengineer.com/practice-sites/practice-tables-selenium/");
      //identify third row from first row in form of list
      List<WebElement> l = driver.findElements(By.xpath ("//table[@id='table1']/tbody/tr[1]/following-sibling::tr[2]/td"));
      //iterate list to get text of third row elements
      for (int i = 0; i<l.size(); i++) {
         String colVal = driver.findElements(By.xpath ("//table[@id='table1']/tbody/tr[1]/following-sibling::tr[2]/td")) .get(i).getText();
         System.out.println("Values at third row after are : " + colVal);
      }
      driver.close();
   }
}

Output

Updated on: 08-Apr-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements