How to Handle Dynamic Webtable in Playwright

 

Handling a dynamic web table in Playwright with Java involves the following steps:















What is a Dynamic Web Table?

A dynamic web table is a table whose rows or columns are populated dynamically, often via JavaScript/AJAX. The number of rows/columns or their contents can change at runtime.


Steps to Handle Dynamic Table in Playwright Java

  • Launch browser and go to the website
  • Identify the table element
  • Use locators to iterate through rows and columns
  • Extract text or perform actions on cells



Example Website

We'll use this dummy site with a dynamic table:

https://demo.guru99.com/test/web-table-element.php

<dependencies>
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.44.0</version>
    </dependency>
</dependencies>




Java Code Example


import com.microsoft.playwright.*;

public class DynamicWebTableExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            Page page = browser.newPage();

            // Navigate to the sample dynamic table page
            page.navigate("https://demo.guru99.com/test/web-table-element.php");

            // Locate the table
            Locator table = page.locator("table.dataTable");

            // Get number of rows (excluding the header row)
            int rowCount = table.locator("tbody > tr").count();
            System.out.println("Total Rows: " + rowCount);

            // Get number of columns (assuming all rows have same number)
            int colCount = table.locator("thead > tr > th").count();
            System.out.println("Total Columns: " + colCount);

            // Print table contents
            for (int i = 0; i < rowCount; i++) {
                for (int j = 0; j < colCount; j++) {
                    String cellText = table.locator("tbody > tr").nth(i).locator("td").nth(j).innerText();
                    System.out.print(cellText + " | ");
                }
                System.out.println();
            }

            browser.close();
        }
    }
}



Explanation

  • table.dataTable – CSS selector for the web table.

  • tbody > tr – All rows in the table body.

  • thead > tr > th – All header columns.

  • We loop over each row and column to print content.

No comments:

Post a Comment