How to get Total Number of Rows and Columns in the Web table using Selenium WebDriver?

In this article i will talk about how to get Total Number of Rows and Columns in the Web table using Selenium WebDriver? Firstly let us get the basic understanding about web table.

Refer below post –

How to handle Dynamic Web Table using selenium Webdriver?

In above blog post, we learned how to get all data from web table. Now, let us see, how can we get the total number of rows and total number of columns in the web table.

Below is the HTML code for sample table.

Observe above HTML code for sample table. We know that, tagname <tr> is to indicate that, it is a row in the web table.

Tagname <tr> will be under tagname <tbody>

So, we need to get WebElement of <tbody> tag, so that we can get the count of <tr> tags & ultimately total number of rows in the web table.

So, Below is the sample code, with which we can get total number of rows in the web table.

WebElement TogetRows = driver.findElement(By.xpath("//table[@id='users_table']/tbody"));
List<WebElement>TotalRowsList = TogetRows.findElements(By.tagName("tr"));
System.out.println("Total number of Rows in the table are : "+ TotalRowsList.size());
In order to get total number of columns in the web table, what we need to do is, count total number of <td> tags in first <tr> tagname.

Below is the sample code, with which we can get total number of columns easily.

WebElement ToGetColumns = driver.findElement(By.xpath("//table[@id='users_table']/tbody/tr"));

List<WebElement> TotalColsList = ToGetColumns.findElements(By.tagName("td"));

System.out.println("Total Number of Columns in the table are: "+TotalColsList.size());
Hope this helps !!!

Leave Comment

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

Looking for learning Framework Development from Scratch? Lookout for Detailed Framework Development videos on YouTube here -

https://www.youtube.com/automationtalks

Get the Framework code at Github Repo: https://github.com/prakashnarkhede?tab=repositories