How to Handle Web Table in Selenium WebDriver

How to Handle Web Table in Selenium WebDriver

Table of Contents

Introduction

Every modern website displays information in tables. You see tables on dashboards, admin portals, banking applications, travel sites, and eCommerce analytics pages. Testers must check values in these tables, compare numbers, validate rows, and extract data for verification. That is why learning how to handle Web Table in Selenium becomes a must-have skill for anyone preparing for automation projects or a Selenium certification course.

Most testers struggle with dynamic tables. These tables change rows after every refresh, load values from APIs, and update using JavaScript. Selenium offers powerful ways to locate table elements, read data, and validate content. When you know how to handle a Web Table in Selenium, you gain the ability to automate data-heavy workflows with accuracy and speed.

This blog explains web tables in Selenium in a practical way. You will learn XPath patterns, row-column traversal, dynamic table handling, and real project examples. You will also see simple step-by-step code samples that you can start practising today. If you are enrolled in a Selenium course online, this guide will build strong confidence in your automation skills.

What Is a Web Table in Selenium?

How to Handle Web Table in Selenium WebDriver

A web table is a structured element on a webpage built using HTML <table>, <tr>, <th>, and <td> tags. Most applications show critical data in table format. Selenium can read this data and interact with specific rows or cells.

A table usually contains:

  • Table Header (<th>) – Describes the columns
  • Rows (<tr>) – Each row holds data
  • Columns (<td>) – Each column inside a row represents a value
  • Nested Elements – Links, buttons, inputs inside table cells

Understanding this structure helps you write automation scripts faster and cleaner. Since many QA interviews include questions on Web Table in Selenium, mastering this topic increases your hiring chances.

Why Web Table Handling Is Important for Testers

Test automation depends on accurate validation. Many companies rely on tables for displaying important data. Here are some real industry examples:

✓ Banking

Bank statements, transaction lists, credit card logs, and payment histories are always displayed in tables.

✓ eCommerce

Order list, customer history, product inventory information, and seller dashboards use tables.

✓ Healthcare

Patient records, appointment lists, drug inventory grids, claim reports.

✓ HRMS & Payroll

Employee lists, leaves, attendance grids, salary structures.

✓ Travel & Logistics

Booking summaries, price comparison sheets, shipment tracking data.

In all these cases, a tester must read values, compare numbers, validate totals, and identify records. Any QA engineer with strong command over Web Table in Selenium becomes an asset in real-world projects. This is why web table handling is a core part of every Selenium certification course.

Types of Web Tables in Selenium

Before writing scripts, you must understand two types of tables.

Static Web Table

A static table does not change frequently. HTML defines all rows and columns in advance.

Example use:

  • A simple employee list
  • Static price list

Dynamic Web Table

A dynamic table changes its values frequently. It loads data using APIs or updates after user actions.

Example use:

  • Live stock market rates
  • Automated dashboards
  • Paginated tables

Dynamic tables require advanced XPath and indexing logic. The next sections will show how to handle both types.

HTML Example of a Simple Web Table

Selenium testing

Here is a small sample table to use in our Selenium examples:

<table id="students">
  <tr>
    <th>Name</th>
    <th>Course</th>
    <th>Score</th>
  </tr>
  <tr>
    <td>John</td>
    <td>Python</td>
    <td>85</td>
  </tr>
  <tr>
    <td>Sara</td>
    <td>Selenium</td>
    <td>92</td>
  </tr>
</table>

We will use this HTML to show how to handle Web Table in Selenium step by step.

How to Locate a Web Table in Selenium

You must first locate the table element.

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

You can also locate rows and columns relative to the table.

Step 1: Count Rows in the Web Table

List<WebElement> rows = table.findElements(By.tagName("tr"));
System.out.println("Total rows: " + rows.size());

Step 2: Count Columns in the Web Table

List<WebElement> columns = rows.get(0).findElements(By.tagName("th"));
System.out.println("Total columns: " + columns.size());

Step 3: Read Data from a Specific Cell

Example: Retrieve data from row 2, column 1.

String cellValue = rows.get(2).findElements(By.tagName("td")).get(0).getText();
System.out.println(cellValue);

Step 4: Read All Data from the Table

for (int i = 1; i < rows.size(); i++) {
    List<WebElement> colData = rows.get(i).findElements(By.tagName("td"));
    for (WebElement cell : colData) {
        System.out.print(cell.getText() + " | ");
    }
    System.out.println();
}

This logic works perfectly for static tables. But most enterprise applications use dynamic tables. Let us handle them next.

How to Handle Dynamic Web Table in Selenium

Dynamic tables are more challenging because:

  • Rows update after page reload
  • Columns may shift
  • Rows may be hidden or paginated
  • JavaScript loads values after few seconds
  • Locators must be robust

This is where mastering advanced XPath patterns becomes important. Every Selenium certification course teaches dynamic XPath deeply because testers use it daily in automation projects.

Reading Dynamic Table Values with XPath

Here are practical ways to handle a Web Table in Selenium for dynamic cases.

Locate a Cell Based on Matching Text

Example: Get the score of the student whose name is “Sara.”

String score = driver.findElement(By.xpath("//table[@id='students']//tr[td[text()='Sara']]/td[3]")).getText();

Click a Button in the Same Row

Dynamic tables often include actions such as “Edit”, “Delete”, “Approve”.

Example:

driver.findElement(By.xpath("//td[text()='John']/following-sibling::td/button[text()='Edit']")).click();

Handle Pagination

Many dynamic tables show 10–20 records per page.

Approach:

  1. Loop through pages
  2. Check if the target value exists
  3. Break the loop after finding value

Example:

boolean found = false;

while (!found) {
    List<WebElement> rows = driver.findElements(By.xpath("//table[@id='students']//tr"));
    for (WebElement row : rows) {
        if (row.getText().contains("Sara")) {
            System.out.println("Record found: " + row.getText());
            found = true;
            break;
        }
    }
    if (!found) {
        driver.findElement(By.xpath("//a[text()='Next']")).click();
    }
}

Real-World Use Cases of Web Tables in Selenium

Searching and Validating Data in Dashboards

QA engineers must compare:

  • Price lists
  • Monthly sales
  • Stock numbers
  • Customer analytics

Automating Reporting Workflows

You can pull data from the table, export it to a file, and validate calculations.

Verifying CRUD Operations

  • Add data → verify in table
  • Edit data → check updated values
  • Delete data → check row removal

Checking Sorting Functionality

When you click a column header, values must sort correctly.

Testing Pagination and Filtering

Filtering, searching, and scrolling depend heavily on table validation.

These tasks become easier once you master Web Table in Selenium techniques.

XPath Strategies for Stable Web Table Automation

Based on table ID

//table[@id='students']//tr

Based on header names

//th[text()='Score']/ancestor::table//tr

Using row and column index

//table/tbody/tr[3]/td[2]

Using relative paths

//td[contains(text(),'Python')]

These XPaths ensure stable locator strategy even when HTML changes.

Common Challenges in Web Table in Selenium Automation

✓ Values Load Late

Solution: Use WebDriverWait.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("students")));

✓ Changing Row Index

Solution: Always use text-based XPath.

✓ Sticky Headers or Frozen Columns

Solution: Scroll using JavaScript Executor.

✓ Pagination

Solution: Loop through pages until value is found.

Every automation project includes these challenges. With proper patterns, a tester can handle them easily.

Best Practices for Handling Web Table in Selenium

  • Always use unique attributes for table identification.
  • Prefer dynamic XPath instead of fixed row-column index.
  • Use explicit waits for dynamic content.
  • Scroll when the table is not fully visible.
  • Handle pagination with loops and conditions.
  • Store frequently used XPaths in variables.
  • Use functions to avoid duplicate code.
  • Validate data before interacting.

These habits make your test scripts cleaner, faster, and more reliable.

Advanced Techniques for Web Table Automation

Extracting an Entire Table into Excel

You can read all table values and store them in an Excel sheet using Apache POI.

Converting Table Data into a List or Map

This allows data comparison during testing.

Example:

Map<String, Integer> scores = new HashMap<>();

Validating Table Sorting

You can read column values into a list, sort the list, and compare with UI values.

Using CSS Selectors

CSS selectors are faster than XPath for some operations.

Example:

table#students tr:nth-child(2) td:nth-child(3)

These modern techniques help you automate enterprise-grade applications.

How Web Table Automation Helps Your Career

Handling Web Table in Selenium is a key skill for automation engineers. Companies test this skill in interviews because:

  • Most enterprise apps use tables
  • Testers must read, compare, and verify UI data
  • Web table automation reduces manual data validation
  • It forms the base for advanced automation frameworks

A student who practices table automation gains an edge in job interviews. These skills are also part of every Selenium certification course and Selenium course online because industry projects depend heavily on table handling.

Full Practical Example: End-to-End Script

How to Handle Web Table in Selenium WebDriver

Below is a complete example using everything you learned.

public class WebTableExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com/table");

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("students")));

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

        for (int i = 1; i < rows.size(); i++) {
            List<WebElement> data = rows.get(i).findElements(By.tagName("td"));
            System.out.println(data.get(0).getText() + " | " + data.get(1).getText() + " | " + data.get(2).getText());
        }

        driver.quit();
    }
}

This example covers:

  • Locators
  • Row traversal
  • Column traversal
  • Reading values

This is the same logic you use in real QA projects.

Key Takeaways

  • You must master Web Table in Selenium to work on real automation projects.
  • Selenium provides simple ways to interact with static and dynamic tables.
  • XPath tricks help you find values based on row, column, and text.
  • Dynamic table handling requires pagination logic, waits, and robust locators.
  • Handling tables is a core feature in every Selenium certification course.
  • Practicing table automation increases hiring chances and boosts your project confidence.

Conclusion

Mastering how to handle Web Table in Selenium gives you stronger automation skills and prepares you for real enterprise projects. Start learning with H2K Infosys to gain hands-on training and practical industry exposure.

Enroll today at H2K Infosys to learn Selenium with real-time examples. Build job-ready automation skills now.

Share this article

Enroll Free demo class
Enroll IT Courses

Enroll Free demo class

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Join Free Demo Class

Let's have a chat