For example, when we compare these two locators:
await expect(page.locator(':text("Please enter a valid email or phone number.")')).toBeVisible();
await expect(page.getByText("Please enter a valid email or phone number.", { exact: true })).toBeVisible();
Would one of these be considered more robust than the other? If so, what is the difference in how they work?
This thread is trying to answer question "Is page.locator() or Playwright built-in locators more robust, and what is the difference in how they work?"
Robust for finding stuff or robust as in expressiveness, XPath for expressiveness wins for sure. Testing where we use 3rd party libraries and ofter no id's i'll need ot search for a node based off a given structure, say a node which had a given pattern where two of it's subnodes have a distinct pattern and that is the only way to get it's their parent node... Just wondering if/when i run across this when there is a shadow dom, XPath locators are noted to not having the ability of piercing the shadow dom, luckily haven't come across that yet...
Related Ask AI answer for "What is the difference between using Playwright's built-in locators and the page.locator() method? Which one is more robust and why?".
Playwright offers a range of built-in locators like getByRole()
, getByText()
, and CSS selectors. These prioritize user-visible elements like text or accessible roles, making them less likely to break when the page changes. They also support custom pseudo-classes like :visible
, :has-text()
, and more.
// Example of using built-in locators
const element = await page.getByText('Hello, World!');
On the other hand, page.locator()
creates a locator using a selector to find an element in the page. It supports CSS and XPath selectors with auto-detection if you omit the prefix (css=
or xpath=
). However, XPath and CSS selectors tied to DOM structure can break when the DOM changes.
// Example of using page.locator()
const element = await page.locator('.my-class');
From this, we can infer that Playwright's built-in locators might be more robust than raw CSS or XPath selectors with page.locator()
. They're designed to handle changes in DOM structure better than raw selectors.
For more details, check out this blog post on understanding the difference between locators and selectors in @playwright/test.
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].