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

What are key locators Playwright supports?

The Answer

Playwright provides 8 built-in semantic locators, plus `locator()` for CSS/XPath. The priority order is: getByRole > getByLabel > getByPlaceholder > getByText > getByAltText > getByTitle > getByTestId > locator(CSS).

Deep Dive Explanation

The priority order isn't arbitrary β€” it aligns with how users and assistive technologies interact with the page. The higher in priority, the more resilient to HTML refactoring and the better the accessibility signal. Only use CSS/XPath when semantic locators are truly insufficient.

example.spec.ts
// Priority 1: Best - Role-based (accessibility)
page.getByRole('button', { name: 'Submit' })

// Priority 2: Form labels
page.getByLabel('Email Address')

// Priority 3: Input placeholders
page.getByPlaceholder('Search...')

// Priority 4: Text content
page.getByText('Welcome back!')

// Priority 5: Image alt text
page.getByAltText('Company Logo')

// Priority 6: Title attribute
page.getByTitle('Close dialog')

// Priority 7: Test ID (explicit contract)
page.getByTestId('submit-btn') // matches data-testid="submit-btn"

// Last resort: CSS / XPath
page.locator('button.primary')
page.locator('//button[@data-action="submit"]')