Playwright offers a variety of locators to help you find elements on a webpage.
The Locator API is a new feature in Playwright. It captures the logic needed to retrieve an element at any moment. Unlike the ElementHandle, which points to a specific element, the Locator API captures the logic of how to retrieve that element.
let locator = page.locator('button');
await locator.click();
Playwright also provides experimental selectors for React and Vue. These selectors allow you to select elements by their component name or property values.
The nth and visible selector engines are another new feature in Playwright. The nth selector engine is equivalent to the :nth-match pseudo class but can be combined with other selector engines. The visible selector engine is equivalent to the :visible pseudo class but can also be combined with other selector engines.
await page.locator('button').first().click();
When selecting elements, it's important not to depend on your DOM structure as it can easily change, causing your tests to fail. Instead, use resilient locators such as getByRole(), which filters elements based on their role attribute value.
let button = page.locator('button').first();
await button.getByRole('button');
You can also generate tests using Playwright's test generator that picks resilient locators prioritizing role, text, and test id attributes.
Remember, Playwright provides a variety of locators to help you select elements on a webpage. Choose the one that best fits your needs.
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].