[Solved] How do I get elements in a table with Playwright? – Playwright

by
Ali Hasan
c# playwright playwright-dotnet

The Problem:

Given a webpage with a complex table structure, containing tables within tables, extract the text values from specific input fields within the innermost table. The table holds information about individuals, and the goal is to retrieve the values associated with two specific individuals.

The Solutions:

Solution 1: How to verify a certain text from a specific column from a Table?

Use Expect to contain text function with combination of Nth to select column and row to verify the expected text from the table.

“`js
await expect(page.locator(‘.my-table-row’).nth(2)).toContainText(‘Steve’);
“`

Solution 2: How to get all values from a specific column in an array?

You can iterate over the elements in the table, and for each one, get the innerText property of the nth column.

“`js
const textsFromNthColumn = [];
const rowCount = await page.locator(‘.table-tbody’).locator(‘tr’).count();

for (let i = 0; i < rowCount; i++) {
textsFromNthColumn.push(await page.locator(‘.table-tbody’).locator(‘tr’).nth(i).locator(‘td’).nth(n).innerText())
} // change n with your column number

console.log(textsFromNthColumn)

Solution 2: Getting Element from Table using Table row and column index

This solution uses a different approach to extract the values from the table. Instead of using the `input` tag, it uses the `nth` method to select the elements based on their position in the table.

First, it counts the number of rows in the table using the CountAsync() method:

var rowCount = await Page.Locator(&quot;//*&#64;summary=\&quot;Planners\&quot;]/ tbody/tr//td/*[contains(@id,&#39;tdrow_&#91;C:1&#93;_txt-tb&#39;)]&quot;).CountAsync();

Then, it iterates through the rows and gets the value of the element in the first column using the GetAttributeAsync() method:

for (int i = 0; i &lt; rowCount; i++)
            {
                var text = await Page.Locator(&quot;//*&#64;summary=\&quot;Planners\&quot;]/ tbody/tr//td/*[contains(@id,&#39;tdrow_&#91;C:1&#93;_txt-tb&#39;)]&quot;).Nth(i).GetAttributeAsync(&quot;value&quot;);
                Console.WriteLine($"Value from row {i}: {text}");
            }

This solution is more efficient because it does not require querying the DOM for each element. It also provides a more direct way to access the values in the table, making it easier to understand and maintain.

Video Explanation:

The following video, titled "Locator - Has & Has Text | Playwright Tutorial part - 69 - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Hey, in this video, we'll learn how to handle dropdown with the playwright locator strategy of has and hasText option.