How to Handle Dynamic Webtable in Playwright

 

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.

A dynamic web table is a table on a web page whose rows and columns are not fixed but change dynamically based on data retrieved from the server or user interaction. Unlike static tables (where the structure and data remain constant), dynamic web tables update in real-time or after user actions such as:

  • Searching or filtering records.
  • Paginating through results.
  • Sorting columns.
  • Loading data via AJAX calls or APIs.

Example: A list of orders in an e-commerce admin panel or employee details in an HR system where rows increase/decrease depending on backend data.


Challenges in Handling Dynamic Web Tables

  • Changing number of rows and columns – You cannot rely on fixed positions.
  • Dynamic IDs or locators – Elements may have auto-generated attributes.
  • Pagination – Data might be spread across multiple pages.
  • Sorting/Filtering – Data order may shift after user interaction.

In Playwright with Java, handling a dynamic web table involves navigating, locating, and extracting the table structure in a way that adapts to data changes:

Identify Table Structure:
  • First, you locate the table as a whole (using <table>, <thead>, <tbody>, <tr>, <td>).
  • Separate header (columns) from body (rows) to know where the actual data lies.
Count Rows and Columns Dynamically
  • Instead of hardcoding row/column numbers, use locators that fetch all available rows/columns at runtime.
  • This ensures that even if the table expands or shrinks, your automation adapts.

Iterating Through Table Data
  • Loop through rows dynamically.
  • For each row, capture all cells (columns) dynamically.
  • This allows you to extract or validate data cell by cell.

Searching for Specific Data
  • Navigate row by row, column by column, to locate a specific value (like “Employee Name = John”).
  • Once found, perform actions such as clicking a related link, button, or checkbox in that row.

Handling Pagination
  • If the table spans across multiple pages, Playwright should detect when the next page is available, navigate, and continue processing rows until the required data is found.

Sorting and Filtering
  • Trigger sort/filter actions (e.g., click on column headers, apply filters).
  • Re-extract table rows after the table reloads to ensure you are validating updated data.

Assertions
  • After locating data, verify correctness (e.g., salary column > 5000, status = Active).
  • Assert based on table content to confirm that the dynamic loading is working as expected.


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















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









Maven Dependency

<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();
        }
    }
}


Code explanation

(a) page.navigate() will navigate to the website
(b) We can locate web table by page.locator()
(c) Then, we are fetching no. of rows excluding header rows 
      by table.locator("tbody > tr").count();
(d) Then, we are fetching no. of columns by table.locator("thead > tr > th").count();


Please Note:
  • 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.


Suggested Posts:

1. BrowserContext in Playwright
2. File Upload in Playwright
3. Comma Selectors in Playwright
4. Thread Local in Playwright
5. Handle GET API in Playwright

File Download in Playwright

In Playwright, file download refers to the process of handling situations where a web application triggers the downloading of files, such as PDFs, CSVs, images, or reports. Normally, when you click a download button or a link that initiates a file download, the browser prompts to save the file. 

In automated testing, Playwright provides a structured way to handle and verify these downloads without manual intervention.

In Playwright Java, downloading a file involves listening for the Download event and then saving the file locally using the download.saveAs() method.


Here’s the theory behind file download in Playwright:


Download Event:

When an action in the browser (like clicking a button or link) triggers a download, Playwright emits a special download event. This allows the test script to detect that a download has started and then capture details about it.

Download Object:

Playwright represents the file download as a Download object. This object contains metadata such as the file’s suggested name, its URL, and a reference to the temporary storage location where the file is initially kept during the download process.

Temporary Storage:

By default, downloaded files are saved to a temporary location. They are not stored permanently until the script explicitly saves them. This ensures tests don’t clutter the file system unless the user specifically chooses to persist the files.

File Path Control:

Playwright allows you to programmatically decide where to save the file. You can move it from the temporary location to a permanent folder on your machine, giving you flexibility in managing test artifacts.

Assertions on Downloads:

Since the Download object provides information like the filename, path, and size, you can add assertions in your tests to confirm that the correct file was downloaded. This helps verify that the application is generating the expected content.


Why Important in Testing:

Handling downloads is critical in end-to-end testing because many applications allow users to export reports, invoices, or other data. Automating this ensures that not only is the UI interaction correct, but also the file itself is generated and downloadable as expected.
















How It Works:

  • Trigger the download action on the page (example: clicking a button or link).
  • Wait for the Download event using page.waitForDownload().
  • Save the file locally using the download.saveAs() method.

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.44.0</version> <!-- or latest -->
</dependency>


Java Code Example to Download File using Playwright


import com.microsoft.playwright.*;

import java.nio.file.Paths;

public class FileDownloadExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
             BrowserContext context = browser.newContext(
	                    new Browser.NewContextOptions().setAcceptDownloads(true)
	                );

            Page page = context.newPage();

            // Navigate to the page that has download link/button
            page.navigate("https://demo.automationtesting.in/FileDownload.html");

            // Click the first download link in the sample Word documents table
            Locator downloadLink = page.locator("a.btn:has-text('Download')");

            // Wait for the download to start and get the Download object
            Download download = page.waitForDownload(() -> {
                downloadLink.click(); // Trigger download
            });

            // Save the downloaded file to local path
            String downloadPath = "samplefile.pdf";
            download.saveAs(Paths.get(downloadPath));

            System.out.println("File downloaded to: " + downloadPath);

            browser.close();
        }
    }
}


Code explanation:

(a) While creating BrowserContext object, we have to do setAcceptDownloads(true)
(b)  Navigate to the page that has download link/button
(c) Click the first download link in the sample Word documents table
(d) Wait for the download to start and get the Download object
(e) Save the downloaded file to local path


Important Points:

  • waitForDownload() ensures Playwright listens for the download triggered by the action inside the callback.

  • You must call download.saveAs(Paths.get(...)) to save the file locally.

  • The file is stored in a temporary directory by default until saved manually.


Suggested Posts:

1. BrowserContext in Playwright
2. File Upload in Playwright
3. Comma Selectors in Playwright
4. Handle Dynamic Webtable in Playwright
5. Page Object Model in Playwright