72 / 139 · 13 Browser Automation with Playwright · Locator Strategies← prev⊞ allnext →☰ Read as one page
7.3CSS and XPath: When You Need Them
Playwright supports CSS and XPath for cases where semantic locators are insufficient:
// CSS selector
await page.locator('.product-card >> .price').textContent();
// XPath (prefix with //)
await page.locator('//div[@class="sidebar"]//a').click();
When CSS/XPath Is Acceptable
- Third-party widgets without accessible roles or test IDs
- Complex DOM traversal (parent → child → sibling relationships)
- Legacy applications where adding test IDs is not possible
When to Avoid CSS/XPath
- Positional selectors like
div:nth-child(3)— break when markup order changes - Deep nesting like
#app > div > main > section > form > button— break on any refactor - Class-based selectors that target styling (
.btn-primary) rather than purpose