PRACTICE
Locators Examples
Examples for CSS selectors, XPath, Playwright locators, and automation-friendly attributes.
๐ฏ getByRole
// Playwright
await page.getByRole('button', { name: 'Add Item' }).click();
await page.getByRole('link', { name: 'Contact' }).click();
๐ getByText
๐ฅ Hot Deal: Buy 1 Get 1 Free
Latest news and updates
await page.getByText('Hot Deal: Buy 1 Get 1 Free').click(); // or assert visible
await expect(page.getByText('Latest news and updates')).toBeVisible();
๐ท️ getByLabel
await page.getByLabel('Choose a country').selectOption('IN');
await page.getByLabel('Email for newsletter').fill('test@example.com');
๐ getByPlaceholder
Try typing:
Aliceawait page.getByPlaceholder('Search by username').fill('Alice');
๐ผ️ getByAltText
Username: Alice
Use image alt text locator for this avatar.
await page.getByAltText('User avatar').click();
await expect(page.getByTestId('username')).toHaveText('Alice');
๐ท️ getByTitle
await page.getByTitle('Settings').click();
๐งช getByTestId
await expect(page.getByTestId('status-banner')).toContainText('All systems operational');
๐งฑ Legacy CSS
This is a legacy CSS target
// CSS selector
page.locator('#legacy-css-target');
page.locator('.legacy-css-target');
// XPath
page.locator("//div[@id='legacy-css-target']");
๐ XPath Practice: List
- Task 1: Review
- Task 2: Implement
- Task 3: Deploy
// XPath examples //ul[@id='tasks']/li[1] //li[contains(text(),'Task 2')] //li[@data-task='3']
๐ XPath Practice: Table
| Product | Status | Stock |
|---|---|---|
| Headphones | Available | 12 |
| Monitor | Out of stock | 0 |
| Keyboard | Available | 5 |
//table[@id='products']//tr[td='Monitor']/td[@data-col='status'] //table[@id='products']//td[@data-testid='cell-stock-1'] //th[normalize-space()='Status']