Search code examples
pythoncss-selectorsplaywright

Playwright get_by_role using nth selector


I'm writing a Playwright test in Python. I have a table that I want to grab every row from to perform some actions within a for loop but I want to skip the first row.

I am able to grab every row within a table by doing something as simple as the following:

table = page.get_by_role("row").all()
for row in table:
    print(row)

But I want it to skip the first row. So I know the css selector for that is :nth-child(n+1) but I'm not sure how to use this in Playwright. I tried doing something like:

table = page.get_by_role("row:nth-child(n+1)")

But I got the error: unexpected symbol ":"

Then I tried:

table = page.get_by_role("row").nth("n+1")

But that also didn't work. Finally, tried this:

table = page.locator("[role=row]:nth-child(n+1)")

But I got the error: ERROR test_table.py - TypeError: 'Locator' object is not iterable

How do I properly query all the rows skipping the first one?


Solution

  • Rather than manipulating the selector, you simply start the for loop at the second element, like this:

    table = page.get_by_role("row").all()
    # Using slice notation
    for row in table[1:]:
        print(row)