How to extract table data using Selenium WebDriver with Java

In the blogpost, we will see how to read cell values from a web table (HTML table) using Selenium WebDriver with Java.

Let us have a look at the automation script that traverse through the web table row, get total number of rows, total number of columns in each row and the values of each cell at last.

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TableDemo {

            public static void main(String[] args) {
                         WebDriver driver = new FirefoxDriver();
                         driver.get(“http://elvery.net/demo/responsive-tables/”);
                         driver.manage().window().maximize();

                        WebElement table =      driver.findElement(By.xpath(“//table[contains(@class,’table-bordered’)]”));
                        List<WebElement> rowsList = table.findElements(By.tagName(“tr”));

                        List<WebElement> columnsList = null;

                       for (WebElement row : rowsList) {
                               System.out.println();
                               columnsList = row.findElements(By.tagName(“td”));

                                for (WebElement column : columnsList) {
                                       System.out.print(column.getText() + “, “);
                               }

                   }
          }
}

Code explanation :

WebElement table = driver.findElement(By.xpath(“//table[contains(@class,’table-bordered’)]”));

The line locates the Web table element by using Xpath.

List<WebElement> rowsList = table.findElements(By.tagName(“tr”));

The above line tries to get all the rows of the web table by tagName (tr).

System.out.println(“Total number of rows : ” + rowsList.size());

The line prints the total number of rows.

for (WebElement row : rowsList) {
         System.out.println();
         columnsList = row.findElements(By.tagName(“td”));

         for (WebElement column : columnsList) {
                    System.out.print(column.getText() + “, “);
         }
}

The above piece of code iterates through the list of rows, gets the list of columns of each row, iterates through each column (in second for loop) and gets the cell value using getText() method.

Hope it helps you !!

Cheers 🙂

 

Advertisements

#get-cell-values-of-table, #get-total-number-of-rows, #iterate-a-web-table, #read-values-from-table