Module 2 of 5

Selectors & Locators

Find any element reliably using Playwright's powerful locator engine.

🎯 The Locator Priority Guide

Playwright recommends using locators in this order — from most to least reliable:

1st
Role-based
page.getByRole('button', { name: 'Submit' })

Most resilient — matches how users perceive the UI

2nd
Text
page.getByText('Sign in')

Great for visible labels & headings

3rd
data-testid
page.getByTestId('login-btn')

Best for CI/CD — engineers add it explicitly

4th
CSS Selector
page.locator('.submit-btn')

Widely used but can break when styles change

5th
XPath
page.locator('//button[@type="submit"]')

Last resort — verbose & brittle

đź”— Chaining & Filtering Locators

chaining-example.spec.ts
// Find a specific row in a table
const row = page.getByRole('row', { name: 'Playwright' });
const editBtn = row.getByRole('button', { name: 'Edit' });
await editBtn.click();

// Filter a list to find a specific item
const items = page.getByRole('listitem');
const targetItem = items.filter({ hasText: 'Playwright' });
await expect(targetItem).toBeVisible();

// Find within a parent container
const form = page.locator('#login-form');
await form.getByLabel('Email').fill('test@example.com');
await form.getByLabel('Password').fill('secret');
.filter() narrows down a list of matching elements
.nth(0) picks the first from multiple matches
.first() and .last() for convenience
Chains are lazy — they don't hit the DOM until an action

🛠️ Pro Tip: Use Playwright's CodeGen

Playwright has a built-in code recorder that writes locators for you as you click!

# Record actions and generate code automatically
npx playwright codegen https://www.careerraah.com

# The browser opens with a recording panel.
# Every click/type generates Playwright code!
📝 Module Quiz

Test Your Knowledge

Score 70%+ to advance to the next module

Question 1 of 4
0 answered

Q1. What is the recommended first-choice locator strategy in Playwright?

Q2. Which Playwright method lets you record selectors automatically by clicking in the browser?

Q3. How do you select the 3rd element in a list of matching locators?

Q4. Which method narrows down a list of locators by filtering on text?