How to count the number of headers in a web table in Selenium?

Software TestingAutomation TestingSelenium Web Driver

The total number of headers in the web table can be counted with the help of findElements() method. The logic is to return a list of web elements with xpath with the help of <th> tag inside the table, then getting the size of that list.

Code Implementation

Example

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class TableHeaderCount {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",       "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // xpath with index appended to get the header
      //from the row 1 of table with the help of <th> tag
      List<WebElement> header = driver.findElements(By.xpath("//table/tbody/tr[1]/th"));
      System.out.println(“The number of table headers is “+ header.size());
      driver.close();
   }
}
raja
Published on 10-Jun-2020 16:09:18
Advertisements