Skip to main content

๐ŸŽฏ 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:

LocatorExample
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:โ€‹

  • button
  • textbox
  • heading
  • link
  • checkbox
  • radio
  • listitem
  • dialog

โœ… 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