To reference UI elements with the same selector in @playwright/test, follow these best practices:
Narrow down your search by filtering locators based on text or another locator. For example, filter a list item by its text content and then select a button within that item using its role attribute.
import { test, expect } from '@playwright/test';
test('example', async ({ page }) => {
await page.goto('https://ray.run/');
const listItem = page.locator('li').withText('Example Item');
const button = listItem.locator('button[role="button"]');
await button.click();
});
Select elements based on their role, name, label, or other attributes visible to users. This makes your tests more resilient to DOM structure changes.
import { test, expect } from '@playwright/test';
test('example', async ({ page }) => {
await page.goto('https://ray.run/');
const button = page.locator('button[aria-label="Example Button"]');
await button.click();
});
Playwright Test provides selector engines like nth-match
and visible
pseudo classes, which can be combined with other selector engines like first()
, nth()
, and last()
.
import { test, expect } from '@playwright/test';
test('example', async ({ page }) => {
await page.goto('https://ray.run/');
const button = page.locator('button:nth-match(2)');
await button.click();
});
By following these practices, you can effectively reference UI elements with the same selector in your @playwright/test tests.
If you still have questions, please ask a question and I will try to answer it.
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].