How to get text from each cell of an HTML table using Selenium?

We can get text from each cell of an HTML table with Selenium webdriver.A <table> tag is used to define a table in an html document. A table consists of rows represented by <tr> and columns represented by <td>. The table headers are identified by <th> tag.

Let us consider a table from which we will get text from each cell.

SeleniumOpen Source
UFTCommercialUNified Functional Tester
TestCompleteCommercialTest Coomplete

Let us see the html code representation for the above table−

To retrieve the rows count of the table, we will use−

List<WebElement> rows =driver.findElements(By.tagName("tr"));

int rws_cnt= rows.size();

To retrieve the columns count of the table, we will use−

List<WebElement> cols =driver.findElements(By.tagName("td"));

int cols_cnt= cols.size();


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;

public class TableCellValue{
   public static void main(String[] args) {
         WebDriver driver = new ChromeDriver();
         String u="";
         driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
         // identify table
         WebElement t = driver.findElement(By.xpath("//*[@id='table1']/tbody"));
         // count rows with size() method
         List<WebElement> rws = t.findElements(By.tagName("tr"));
         int rws_cnt = rws.size();
         //iterate rows of table
         for (int i = 0;i < rws_cnt; i++) {
         // count columns with size() method
         List<WebElement> cols = rws.get(i).findElements(By.tagName("td"));
         int cols_cnt = cols.size();
         //iterate cols of table
         for (int j = 0;j < cols_cnt; j++) {
         // get cell text with getText()
         String c = cols.get(j).getText();
      System.out.println("The cell value is: " + c);