πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 55 of 100
Locators
Intermediate

Why are Playwright locators considered more reliable than CSS/XPath?

The Answer

Playwright's built-in locators (`getByRole`, `getByLabel`, etc.) are based on user-visible attributes and accessibility semantics rather than DOM structure. This makes them resilient to internal HTML refactoring.

Deep Dive Explanation

CSS and XPath describe WHERE an element is in the DOM. Playwright locators describe WHAT an element IS (its role and name). Developers frequently refactor HTML structure, but they rarely change what a button does or what a label says. This is why semantic locators have dramatically lower maintenance costs.

example.spec.ts
// BRITTLE: CSS selector breaks when HTML structure changes
await page.locator('div.container > div:nth-child(3) > button').click();

// BRITTLE: XPath breaks when nesting changes
await page.locator('//div[@class="modal"]//button[contains(@class,"submit")]').click();

// RESILIENT: getByRole survives any HTML restructuring
await page.getByRole('button', { name: 'Submit Order' }).click();

// RESILIENT: getByLabel survives class/id changes
await page.getByLabel('Email address').fill('user@example.com');