๐ฏ Module 4 โ Locators & Selectors
Locators are the most important concept in Playwright.
They help you find elements on a webpage so you can interact with them.
โ Types of Locatorsโ
Playwright gives us multiple ways to find elements:
| Locator | Example |
|---|---|
getByRole() | Best practice |
getByText() | Find by visible text |
getByLabel() | Find by form label |
getByPlaceholder() | Find by placeholder |
getByTestId() | Find by data-testid |
locator() | CSS / XPath fallback |
โ 1. getByRole()โ
The most recommended locator in Playwright.
// Click a button
await page.getByRole('button', { name: 'Submit' }).click();
// Find a textbox
await page.getByRole('textbox', { name: 'Email' }).fill('test@test.com');
// Find a heading
await page.getByRole('heading', { name: 'Welcome' });
// Find a link
await page.getByRole('link', { name: 'Home' }).click();
Common Roles:โ
buttontextboxheadinglinkcheckboxradiolistitemdialog
โ 2. getByText()โ
Find elements by their visible text.
// Click element with exact text
await page.getByText('Sign In').click();
// Case insensitive match
await page.getByText(/sign in/i).click();
โ 3. getByLabel()โ
Best for form inputs.
await page.getByLabel('Email').fill('user@test.com');
await page.getByLabel('Password').fill('password123');
โ 4. getByPlaceholder()โ
Find inputs by placeholder text.
await page.getByPlaceholder('Enter your email').fill('user@test.com');
โ 5. getByTestId()โ
Best for stable automation โ requires data-testid in HTML.
await page.getByTestId('login-button').click();
HTML looks like:
<button data-testid="login-button">Login</button>
โ 6. locator() โ CSS Selectorโ
Use when other locators don't work.
// By CSS class
await page.locator('.submit-btn').click();
// By name attribute
await page.locator('textarea[name="q"]').fill('Playwright');
// By ID
await page.locator('#email').fill('user@test.com');
โ 7. locator() โ XPathโ
Use as last resort only.
await
---
## ๐ Keep Going
Apply what you learned in this module:
- ๐งช **[Practice Exercises](./practice)** โ hands-on tasks to build real skills
- ๐๏ธ **[Real Projects](./real-projects)** โ real-world automation examples