You can easily iterate over each cell in a table using Playwright's locators. Here's how you can do it:
First, locate the table using getByRole()
with 'table' as its argument. This will return a locator representing the entire table element. Then, call getAllByRole()
on this locator with 'row' as its argument to get an array of locators for each row in the table.
const table = await page.getByRole('table');
const rows = await page.getAllByRole('row', { within: table });
Next, use a for loop to iterate over each row of the table. Within each iteration, use another for loop to iterate over each column of that row.
for (let i = 0; i < rows.length; i++) {
const cells = await page.getAllByRole('cell', { within: rows[i] });
for (let j = 0; j < cells.length; j++) {
// Do something with this cell
console.log(await cells[j].textContent());
}
}
In this code snippet, we first locate the entire table
element. We then get an array of all tr
elements within it. We start our outer for loop which iterates over every row. Within each iteration, we call getAllByRole()
again but with 'cell'
as its argument and { within: rows[i] }
as options object so that we only search for cells inside the current row. Finally, we start our inner for-loop which iterates over every cell in the current row.
This way, you can access all elements inside a HTML Table using Playwright's powerful API!
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].