How to handle webtable in Selenium WebDriver

WebTables are a very important part of any web-based application and Often we come across a scenario where we have to validate data in a web table. Here we have a complete example code related to a web table on a webpage which will help you to get data from a Web table in Selenium WebDriver using java. 

Types of web tables and tags

Web tables are created mainly in the following two ways.

  1. By using the tags such as <th>, <tr>, and <td> for header, row, and cell respectively.
  2. The other way is to use <mat-header>, <mat-row>, and <mat-cell> for header, row, and cell respectively.

This is important to know because in our approach to fetch the contents of the cells in the table we are using the findElement(By.tagName()) method.

This method considers the table to have row tag= “tr” and cell tag to be= “td“. You can replace the tag value based on your table tag such as tr with mat-row and td with mat-cell etc. and it will work without any issue. 

Example code to handle Web table in Selenium WebDriver

In order to handle and read data from the web table in Selenium, this function will take the XPath of the web table as an argument and return the contents of the web table as a two-dimensional array.

 * This method returns all the data from webtable in 2d array
 * Considering table is created with tr and td tags
 * Can change the row and cell tags for other table tags i.e. mat-row & mat-cell
 * @param driver  WebDriver driver
 * @param tableXpath WebTable xpath where data needs to be fetched from
 * @return Returns 2d array with table data
public static String[][] getWebTableData(WebDriver driver, String tableXpath) {
	String tempCellText;
	WebElement table = driver.findElement(By.xpath(tableXpath));
	List <WebElement> rowsList = table.findElements(By.tagName("tr"));
	int numRows = rowsList.size();
	int numCols = rowsList.get(0).findElements(By.tagName("td")).size();

	System.out.println("Total number of rows= " + numRows);
	System.out.println("Total number of cols=" + numCols);

	String[][] arrTabledata = new String[numRows][numCols];
	List < WebElement > columnsList = null;

	for (int i = 0; i < numRows; i++) {
		columnsList = rowsList.get(i).findElements(By.tagName("td"));
		for (int j = 0; j < numCols; j++) {

			System.out.print(columnsList.get(j).getText().toString() + ",");
			tempCellText = columnsList.get(j).getText();
			arrTabledata[i][j] = tempCellText.toString();
		System.out.println("Next Row");
	return arrTabledata;

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *