← Back to Discord Forum

How to use rectangle axis of a page to locate an item?

foreverpianoposted in #help-playwright
Open in Discord

Is there any api in playwright working? I want to choose a tag or buttom using the absolute loction of the page.

This thread is trying to answer question "Is there any API in Playwright that allows selection of a tag or button using the absolute location on the page?"

0 replies


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.

Related Discord Threads

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.