Chapter 39: XPath and locator filtering
Automation learning lab
Playwright Automation
Self Study Guide
Start from zero. Learn JavaScript and TypeScript, automate browsers, and build reliable end-to-end tests.
XPath and locator filtering
XPath selects DOM nodes using path expressions, but long structural paths can break after layout changes. Locator filter narrows matches using text or related locators. Playwright actions generally require exactly one matching element.
How it works
Step-by-step walkthrough
- Create two product rows
- Filter the target row
- Click its button
Example
import { test, expect } from '@playwright/test';
test('chapter 39 practice', async ({ page }) => {
await page.setContent('<ul><li>Basic <button>Buy</button></li><li>Pro <button>Buy</button></li></ul>');
const row = page.getByRole('listitem').filter({ hasText: 'Pro' });
await row.getByRole('button', { name: 'Buy' }).click();
});Prefer filtering semantic locators over absolute XPath.
Practice application screenshot
✎ Your practice task
Locate the same row with locator('xpath=//li[contains(., "Pro")]') and compare.
Knowledge check
What does filter({ hasText: 'Pro' }) do?
🌐 Continue learning
60-chapter learning path
Start at chapter 1, or choose any topic. Your progress is tracked separately for each chapter.
JavaScript fundamentals
TypeScript fundamentals
Playwright • setup & locators
Playwright • interactions & assertions
Playwright • framework & debugging
Playwright • real-world automation
Interactive practice lab
Try the controls below and observe the corresponding Playwright locator instructions. This browser demo does not execute Node.js or Playwright Test; copy the code to your local Playwright project to automate it.
Task manager demo
Suggested automation
Actions on the demo update these examples. In your local test use a page that contains the same controls.
Download a standalone lab page, then serve it locally (for example with Python's http.server). Navigate to it in a Playwright test.