Rayrun

How do I select and interact with elements on a webpage using Playwright?

Answer

Sure, you can select and interact with elements on a webpage using Playwright. It's pretty straightforward. You can use CSS selectors, XPath selectors, or test ids.

For instance, in your HTML, you can use data-pw as your test id. Here's an example:

<button data-pw="directions">Itinéraire</button>

Then, in your script, you can locate this element like this:

await page.getByTestId('directions').click();

If you prefer CSS or XPath locators, Playwright got you covered. Use page.locator() to create a locator. Here are some examples:

await page.locator('css=button').click();
await page.locator('xpath=//button').click();
await page.locator('button').click();
await page.locator('//button').click();

But remember, long chains of CSS or XPath selectors are not recommended. They're tied closely to the DOM structure which may change over time.

Instead, use locators that reflect how users perceive the webpage. For instance, role locators or explicit testing contracts using test ids.

Playwright also introduces new locator APIs which represent views into elements on a webpage. These locators capture logic sufficient enough for retrieving an element at any given moment. Here's how you can use it:

const locator = page.locator('button');
await locator.click();

So, while there isn't any specific API in Playwright for selecting tags/buttons based on their absolute location on a webpage, there are several ways to select elements reliably even when changes occur in DOM structure.

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 [email protected].