Locators in Playwright – CSS Selector vs XPath
When automating tests, we need to locate elements on a web page to interact with them. Apart from Playwright’s built-in locators (getByRole
, getByText
, etc.), two traditional locator strategies are:
- CSS Selector
- XPath
Let’s explore them one by one with Playwright examples.
1. CSS Selector
What is a CSS Selector?
- A CSS Selector is a query language used in web development to style elements and in automation to locate elements.
- It selects elements using IDs, classes, attributes, or hierarchy in the DOM.
- Playwright defaults to CSS when no prefix is provided.
Example – CSS Selector in Playwright
CSSSelector.spec.ts
test('Locator with CSS Selector', async ({ page }) => {
// Launch application
await page.goto('https://vinothqaacademy.com/demo-site/');
// First name (using CSS ID selector)
await page.locator('css=#vfb-5').fill('Vinoth');
// Last name (short form without "css=")
await page.locator('#vfb-7').fill('R');
});
Advantages of CSS Selector
- Simple, short, and easy to read.
- Faster since browsers natively support CSS queries.
- Great for IDs, classes, and attribute-based selection.
2. XPath Selector
What is XPath?
- XPath (XML Path Language) is a query language that navigates the DOM like a map.
- It can locate elements using attributes, text content, and hierarchical relationships.
- Unlike CSS, XPath can move both forward and backward in the DOM tree.
Example – XPath in Playwright
XPath.spec.ts
test('Locator with XPath Selector', async ({ page }) => {
// Launch application
await page.goto('https://vinothqaacademy.com/demo-site/');
// Email Id (explicit XPath)
await page.locator("xpath=//input[@id='vfb-14']").fill('vinothrwins@gmail.com');
// Mobile Number (short form without "xpath=")
await page.locator("//input[@id='vfb-19']").fill('123456789');
});
Advantages of XPath
- Can navigate parent, child, and sibling relationships.
- Works even when elements don’t have IDs or classes.
- Can locate elements by visible text.
CSS Selector vs XPath
Feature | CSS Selector | XPath |
Syntax | Short, clean | Verbose, complex |
Speed | Faster (browser-native) | Slower than CSS |
Navigation | Forward only | Forward + backward |
Readability | Easy for beginners | Harder for beginners |
Best For | IDs, classes, attributes | Complex DOM, text-based search |
🚀 Key Takeaway #
- Prefer Playwright’s built-in locators (
getByRole
,getByLabel
, etc.) → stable and readable. - Use CSS selectors for quick, clean, and fast element targeting.
- Use XPath only when necessary, such as:
- Complex DOM structures
- Locating by text
- Navigating parent/child/sibling relationships
Vinoth Hack: Use the Playwright locator pick-up 😊 Let the tool decide first, and then you can refactor the code 😊