How do I select a specific element in Playwright?


Selecting Elements in Playwright

When it comes to selecting elements in Playwright, it's all about chaining and filtering locators. This approach allows you to zero in on a specific part of the page. For instance, you can use the getByRole method to grab a list item and then filter it by text using the hasText property. This way, you can pinpoint a particular product on the page that matches your criteria.

const listItem = page.locator('li').first();
const product = listItem.locator(':has-text("Your Product")');

Avoid using CSS selectors or XPath expressions as they depend on specific DOM structures that may change over time. Instead, opt for user-facing attributes like button labels or input field names. These are visible and meaningful to users, making your tests more resilient.

If you're unsure about which locator to use, Playwright's test generator, codegen, is your friend. It generates locators based on role, text, and test ID locators. To use codegen, run the command followed by the URL of the page.

npx playwright codegen https://ray.run

Once generated, these locators can be used with various methods such as click() or type(). So, remember to chain and filter locators, use user-facing attributes, and leverage codegen when in doubt. Happy testing with Playwright!

For more insights, check out Understanding the Difference Between Locators and Selectors in @playwright/test.


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 Questions

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.