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:
page.getByRole('button', { name: 'Submit' })Most resilient — matches how users perceive the UI
page.getByText('Sign in')Great for visible labels & headings
page.getByTestId('login-btn')Best for CI/CD — engineers add it explicitly
page.locator('.submit-btn')Widely used but can break when styles change
page.locator('//button[@type="submit"]')Last resort — verbose & brittle
đź”— Chaining & Filtering Locators
// 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🛠️ 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!
Test Your Knowledge
Score 70%+ to advance to the next module
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?