How to handle Web Tables in Selenium

A practical guide to identify rows, columns, and cells in dynamic HTML tables using Selenium for test automation.

Guide Banner Image
Home Guide How to handle Web Tables in Selenium

How to handle Web Tables in Selenium

Web tables are a common way to display structured data on websites, such as dashboards, reports, product listings, or user records. For QA engineers and automation testers, verifying the content and structure of these tables is a critical part of ensuring application reliability. Selenium WebDriver provides powerful capabilities to locate, interact with, and validate table data.

In this article, you’ll learn how to handle both static and dynamic web tables in Selenium using practical examples, helping you build robust test scripts that cover real-world scenarios.

What are Web Tables?

Web Tables are like normal tables where the data is presented in a structured form using rows and columns. The only difference is that they are displayed on the web with the help of HTML code.

<table> is the HTML tag that is used to define a web table. While <th> is used for defining the header of the table, <tr> and <td> tags are used for defining rows and columns respectively for the web table.

Example of writing a web table using HTML:

<table>
 <tr>
  <th>First Name</th>
  <th>Last Name</th>
  <th>Age</th>
 </tr>
 <tr>
  <td>Jill</td>
  <td>Ann</td>
  <td>24</td>
 </tr>
 <tr>
  <td>Eve</td>
  <td>Anderson</td>
  <td>34</td>
 </tr>
</table>

Web Table Example

Web Table Example

Why is Handling Web Table in Selenium important?

Web tables often contain critical data that drives user decisions, such as pricing, inventory, user information, or transaction history. Ensuring this data is displayed correctly and functions as expected is vital for application quality.

Handling web tables in Selenium is important because it allows testers to:

  • Verify dynamic data rendered from APIs or databases.
  • Validate sorting, filtering, and pagination functionalities.
  • Perform actions within table cells like clicking buttons, checking boxes, or editing inputs.
  • Ensure consistency across different browsers and devices.

By automating these checks, you can detect issues early, reduce manual effort, and improve the reliability of your application’s data presentation.

Types of Web Tables

Depending on the data in the table, web tables can be classified as Static web tables and Dynamic web tables.

1. Static Web Tables

These tables have fixed data that remains unchanged throughout. Due to the static nature of their content, they are called Static web tables.

2. Dynamic Web Tables

These tables have data that changes over time, and hence the number of rows and columns might also change depending upon the data shifts. Due to the dynamic nature of their content, they are called Dynamic web tables.

Often, the functionalities of web applications depend on the data carried by Dynamic web tables, as they act as the data source for the functional modules in many cases. Thus, handling dynamic web tables using Selenium WebDriver is essential for QAs to run test cases that determine website performance.

How to handle dynamic web tables in Selenium?

Understand handling web tables in Selenium with the help of an example. The example uses the data presented using web tables on the IPO Filings Data section of the NYSE (New York Stock Exchange) website to demonstrate the process.NYSE Web Tables Example Copy Xpath

Dynamic Web Table on the IPO Filings Data page of NYSE

Locating Web Tables in the DOM

Before interacting with a web table using Selenium, it’s crucial to understand how tables are structured in the HTML DOM. Most web tables use a combination of the following tags:

  • <table> – defines the table itself
  • <thead> – contains header rows
  • <tbody> – contains the main data rows
  • <tr> – defines each row
  • <th> – defines a header cell
  • <td> – defines a standard cell

Common Strategies to Locate Tables in Selenium

Here are some of the common strategies to locate tables in Selenium:

1. By Tag Name

java

WebElement table = driver.findElement(By.tagName("table"));

2. By ID or Class

If the table has a unique identifier:

java

WebElement table = driver.findElement(By.id("userTable"));

// or

WebElement table = driver.findElement(By.className("data-table"));

3. By XPath

Useful for complex structures:

java

WebElement table = driver.findElement(By.xpath("//table[@id='userTable']"));

4. By CSS Selector

Ideal for selecting based on classes or attributes:

java

WebElement table = driver.findElement(By.cssSelector("table.data-table"));

Once the table element is located, you can use nested findElements() calls to traverse rows and columns, making it possible to extract or validate data efficiently.

Finding XPath Dynamic Web Table

Select an element in the web table and find its XPath. For Chrome, right-click and inspect the given element to find its XPath.

To find the XPath of a UI element in Firefox, right-click on the desired element, go to “Inspect Element” to open the inspector which will help identify its XPath.

NYSE Web Tables Example Copy Xpath

Finding XPath of selected element using Inspect Element for Google Chrome

Finding the number of rows and columns of Dynamic Web Table in Selenium

Here’s the code snippet to find the total number of rows and columns for the above Dynamic Web Table

//Finding number of Rows
List<WebElement> rowsNumber = driver.findElements(By.xpath(“//*[@id="content-8b4988b9-2ec9-4e77-9b4d-9c2994bd9e8a"]/div/div/table[1]/tbody/tr[1]/td[1]”));
int rowCount = rowsNumber.size();
System.out.println("No of rows in this table : " + rowCount);

Output: No of rows in this table: 8

//Finding number of Columns
List<WebElement> columnsNumber = driver.findElements(By.xpath("//*[@id="content-8b4988b9-2ec9-4e77-9b4d-9c2994bd9e8a"]/div/div/table[1]/thead/tr/th[1]"));

int columnCount = columnsNumber.size();
System.out.println("No of columns in this table : " + columnCount);

Output: No of columns in this table: 9

Run Selenium Tests on Cloud for Free

Finding cell value for specific row & column of Dynamic Web Table in Selenium

Identify the data present in the 6th Row and 6th Column of the given dynamic web table on the IPO Filings Data page of the NYSE website:

WebElement cellAddress = Rowtable.findElement(By.xpath(“//*[@id="content-8b4988b9-2ec9-4e77-9b4d-9c2994bd9e8a"]/div/div/table[1]/tbody/tr[4]/td[3]”));
String value = cellAddress.getText();
System.out.println(“The Cell Value is : “ +value);

Output: The Cell Value is: OLMA

Interacting with Table Elements

Beyond reading data, many web tables include interactive elements like buttons, checkboxes, dropdowns, or input fields within their cells.

Automating these interactions with Selenium is essential for validating real-world workflows such as editing records, selecting rows, or triggering actions from a table.

Common Interactions in Web Tables

1. Clicking a Button in a Table Cell

java

WebElement button = driver.findElement(By.xpath("//table[@id='userTable']/tbody/tr[2]/td[5]/button"));

button.click();

2. Selecting a Checkbox in a Row

java

WebElement checkbox = driver.findElement(By.xpath("//table[@id='userTable']/tbody/tr[3]/td[1]/input[@type='checkbox']"));

checkbox.click();

3. Entering Text into an Input Field in a Table

java

WebElement inputField = driver.findElement(By.xpath("//table[@id='userTable']/tbody/tr[1]/td[3]/input"));

inputField.sendKeys("New Value");

4. Selecting an Option from a Dropdown in a Cell

java

Select dropdown = new Select(driver.findElement(By.xpath("//table[@id='userTable']/tbody/tr[4]/td[2]/select")));

dropdown.selectByVisibleText("Approved");

5. Conditional Interaction Based on Cell Content

Loop through rows to find a cell with specific text, then act on that row:

java

List<WebElement> rows = driver.findElements(By.xpath("//table[@id='userTable']/tbody/tr"));

for (WebElement row : rows) {

    String status = row.findElement(By.xpath("td[3]")).getText();

    if (status.equals("Pending")) {

        row.findElement(By.xpath("td[5]/button")).click();

        break;

    }

}

These interactions help simulate real user behavior and validate application logic, making your Selenium tests more comprehensive and valuable.

Talk to an Expert

Handling Tables with Nested Elements

table cells often contain nested elements like dropdowns, buttons, links, icons, or even other tables. These complex structures require precise DOM navigation and dynamic locators when automating tests with Selenium.

Common Scenarios and How to Handle Them

1. Dropdowns inside Table Cells

java

WebElement dropdownElement = driver.findElement(By.xpath("//table[@id='orderTable']/tbody/tr[2]/td[4]/select"));

Select dropdown = new Select(dropdownElement);

dropdown.selectByVisibleText("Shipped");

2. Links or Icons within a Cell

java

WebElement editIcon = driver.findElement(By.xpath("//table[@id='userTable']/tbody/tr[1]/td[6]/a[@class='edit-icon']"));

editIcon.click();

3. Nested Tables

Sometimes a cell may contain a mini-table:

java

WebElement nestedTable = driver.findElement(By.xpath("//table[@id='mainTable']/tbody/tr[3]/td[2]//table"));

List<WebElement> nestedRows = nestedTable.findElements(By.tagName("tr"));

4. Multiple Elements in One Cell (e.g., icon + text + button)

java

WebElement cell = driver.findElement(By.xpath("//table[@id='productTable']/tbody/tr[5]/td[3]"));

String price = cell.findElement(By.className("price-text")).getText();

cell.findElement(By.tagName("button")).click(); // Click 'Add to Cart' button

5. Handling Dynamic Nested Elements with Waits

When elements load asynchronously:

java

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement dynamicIcon = wait.until(ExpectedConditions.visibilityOfElementLocated(

    By.xpath("//table[@id='dataTable']/tbody/tr[2]/td[4]//span[@class='status-icon']")

));

dynamicIcon.click();

Tips:

  • Use relative XPath to scope searches within a row or cell.
  • Always use explicit waits for dynamic/nested elements to avoid NoSuchElementException.
  • For better readability, store parent rows or cells as WebElement and navigate from there.

How to get table data in Selenium Webdriver Java?

To extract data from a web table using Selenium WebDriver in Java, follow these basic steps:

1. Locate the Table

Identify the table element using By.id, By.xpath, or other locators.

java

WebElement table = driver.findElement(By.id("exampleTable"));

2. Get All Rows

Use .findElements() to retrieve all rows inside the table body:

java

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

3. Loop Through Rows and Cells

Iterate through each row and extract cell (<td>) values:

java

for (WebElement row : rows) {

    List<WebElement> cells = row.findElements(By.tagName("td"));

    for (WebElement cell : cells) {

        System.out.print(cell.getText() + " ");

    }

    System.out.println();

}

4. (Optional) Skip Header Row

If the table has a header row (<th>), you can skip it:

java

for (int i = 1; i < rows.size(); i++) {

    List<WebElement> cells = rows.get(i).findElements(By.tagName("td"));

    // Continue as above

}

Example: Fetching Specific Cell Data

java

String cellValue = table.findElement(By.xpath("//tr[2]/td[3]")).getText();

System.out.println("Cell Value: " + cellValue);

This method works well for static and moderately dynamic tables. For more complex tables (e.g., with pagination or dynamic loading), additional handling may be needed using waits or scrolling.

Complete Code for handling Web Tables in Selenium

Purpose: Identify the number of rows & columns and fetch the cell value for a given row and column from the IPO Filing Data web table on the NYSE website using Selenium

//Opening Chrome Browser
package browser;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserSelection
{
static WebDriver driver;

public static WebDriver usingChrome()
{
System.setProperty("webdriver.chrome.driver", "E:\SeleniumLibs\\chromedriver_win32\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
return driver;
}
}

//Test to handle dynamic web table using Selenium WebDriver

package dynamicwebtable;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import browser.BrowserSelection;

public class DynamicWebTableTest
{
WebDriver driver;

@BeforeMethod
public void openBrowser()
{

driver = BrowserSelection.usingChrome();
}

@Test
public void tripDetails() throws InterruptedException, AWTException
{

//Modify Wait time as per the Network Ability in the Thread Sleep method

driver.get("https://www.nyse.com/ipo-center/filings");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(5000);

//Finding number of Rows

List<WebElement> rowsNumber = driver.findElements(By.xpath("//*[@id="content-8b4988b9-2ec9-4e77-9b4d-9c2994bd9e8a"]/div/div/table[1]/tbody/tr[1]/td[1]"));
int rowCount = rowsNumber.size();
System.out.println("No of rows in this table : " + rowCount);

//Finding number of Columns

List<WebElement> columnsNumber = driver.findElements(By.xpath("//*[@id="content-8b4988b9-2ec9-4e77-9b4d-9c2994bd9e8a"]/div/div/table[1]/thead/tr/th[1]"));
int columnCount = columnsNumber.size();
System.out.println("No of columns in this table : " + columnCount);

//Finding cell value at 4th row and 3rd column

WebElement cellAddress = Rowtable.findElement(By.xpath(“//*[@id="content-8b4988b9-2ec9-4e77-9b4d-9c2994bd9e8a"]/div/div/table[1]/tbody/tr[4]/td[3]”));
String value = cellAddress.getText();
System.out.println(“The Cell Value is : “ +value);

driver.quit();
}

}

BrowserStack Automate Banner

Best Practices for Web Table Automation

Automating web tables in Selenium can become complex, especially with dynamic content, pagination, and nested elements. Following best practices ensures your test scripts are reliable, maintainable, and scalable.

1. Use Stable and Unique Locators

  • Prefer id, data-* attributes, or stable class names over absolute XPath.
  • Keep your selectors resilient to layout or content changes.

2. Scope Your Searches

  • Locate the row first, then find specific cells or elements within it.

This reduces errors and makes your code more readable:

java

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

String name = row.findElement(By.xpath("td[2]")).getText();

3. Avoid Hard-Coding Indexes

  • Use header labels or dynamic logic instead of fixed row/column indices where possible.
  • This improves adaptability to table structure changes

4. Use Explicit Waits

  • Always wait for the table and its contents to load before interacting.
  • Prevent flaky tests by using WebDriverWait and ExpectedConditions.

5. Handle Pagination Smartly

  • Create reusable logic to loop through all pages when needed.
  • Ensure you don’t miss rows split across pages.

6. Validate Data, Not Just Presence

  • Go beyond checking if elements exist—verify actual data values for accuracy.
  • Use assertions to compare expected and actual values.

7. Modularize Code

  • Create reusable methods for actions like fetching row count, extracting cell values, or interacting with dropdowns.
  • Keeps test cases clean and maintainable.

8. Log and Report Clearly

  • When validating large datasets, include helpful logs for mismatches.
  • Useful for debugging and review.

9. Account for Dynamic Content

  • If data updates frequently (like dashboards), ensure your tests adapt to changes in content or row order.

10. Test Cross-Browser

  • Web tables may render differently in some browsers. Use tools like BrowserStack to test across environments.

Why choose BrowserStack to run Web Table tests in Selenium?

Running Selenium tests on BrowserStack Automate ensures your web table validations are not only accurate but also reliable across real-world environments. Here’s why it’s a smart choice:

Key Benefits

1. Real Device and Browser Testing

  • Validate table rendering and functionality on 3,500+ real devices and browsers.
  • Ensure your web tables behave consistently across different resolutions, OS versions, and browser engines.

2. Parallel Test Execution

  • Run multiple Selenium scripts in parallel to reduce test time.
  • Ideal for validating web tables across many pages, datasets, or user flows efficiently.

3. Zero Setup, Instant Access

  • No need to maintain local infrastructure or virtual machines.
  • Start testing instantly with pre-configured browser-device combinations.

4. Supports Dynamic Content Testing

  • Web tables often fetch dynamic data. BrowserStack’s real-time testing ensures accurate interaction and validation even with JS-heavy tables.

5. CI/CD Integration

  • Seamlessly plug into CI pipelines using Jenkins, GitHub Actions, or other tools.
  • Run table verification tests automatically on every build or deploy.

6. Detailed Debugging Tools

  • Access screenshots, video recordings, and logs for every test.
  • Quickly identify issues in table loading, alignment, or interaction.

7. Geolocation and Network Simulation

  • Test how web tables load and perform under various network conditions or regions.

Using BrowserStack with Selenium helps you catch layout, data, or interaction issues in web tables early, giving users a smooth experience across all devices and platforms.

Conclusion

As demonstrated, handling the dynamic web table on a website is easy enough using Selenium. Run the code, evaluate the results, and start applying the same process to websites with this particular functionality.

It is important to run Selenium tests on real browsers and devices to ensure testing in real user conditions. BrowserStack offers a Cloud Selenium Grid of 3500+ real browsers and devices for testing purposes. Simply sign up, choose the required device-browser-OS combination from the real device cloud, and start testing websites for free.

Run Selenium Tests on Real Devices

Tags
Automation Testing Selenium Selenium Webdriver