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

SeleniumAutomation TestingTesting Tools

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.

AUTOMATION TOOLTYPELINNK
SeleniumOpen Sourcehttps://www.selenium.org/
UFTCommercialUNified Functional Tester
RanorexCommercialhttps://www.ranorex.com/
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();

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 TableCellValue{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
         WebDriver driver = new ChromeDriver();
         String u="https://sqengineer.com/practice-sites/practice-tables-selenium/";
         driver.get(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);
   }
}
      driver.quit();
   }
}

Output

raja
Published on 18-Sep-2020 11:42:29
Advertisements