dealing with multiple locators in playwright is simple and is made simple straight out of the box.
In this video tutorial, Jared from commit quality provides a detailed guide on how to find and interact with multiple elements on a webpage using Playwright test. He walks us through the process using a computer database website. The tutorial starts with identifying various computer names on the webpage and explaining the structure of the web elements.
Jared then steps into the code, and using Playwright's locator, builds a locator that finds all the computer names on the webpage using a mix of tags and attributes. With the help of console.log and running "npx playwright test", he successfully finds the same number of elements as displayed on the webpage
Jared elaborates on three ways to work with multiple elements using Playwright: .first()
, .last()
and .nth()
. He demonstrates this using a .click()
action on the selected elements. The first method clicks the first element in the list, while the last method does the same but for the last element in the list. Both methods return exactly the expected output.
The nth()
method comes into play when you need to interact with the middle elements in the list (not the first or last) and want to select them by their position. This method is zero-based, meaning that if you’re looking for the third element, you'd use nth(2)
. He shows a practical example of this using the list of computer names on the webpage.
Towards the end of the video, he advises that these methods heavily rely on the structure of the Document Object Model (DOM) and cautions that changes in it can break the process. Therefore, understanding when to use these methods is crucial. These methods can come in handy when you want to interact with the first, last, or nth element without relying on specific attribute values.
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].