Rayrun

What is the difference between using Playwright's built-in locators and the page.locator() method? Which one is more robust and why?

Answer

Comparing Playwright's Built-In Locators and page.locator()

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.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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 luc@ray.run.