Locators (getByRole, getByText)

Playwright locators are auto-waiting and auto-retrying. Prefer role-based and semantic locators.

Semantic locators (preferred)

typescript
// By accessible role
await page.getByRole('button', { name: 'Login' }).click();

// By label (form fields)
await page.getByLabel('Email').fill('alice@example.com');

// By placeholder
await page.getByPlaceholder('Search...').fill('test');

// By text
await page.getByText('Welcome back').isVisible();

// By test ID (data-testid attribute)
await page.getByTestId('submit-btn').click();

// By alt text (images)
await page.getByAltText('Company logo').isVisible();

// By title
await page.getByTitle('Close dialog').click();

CSS / XPath / nth locators

typescript
// CSS selector
await page.locator('.nav-menu a').first().click();

// XPath
await page.locator('xpath=//button[contains(text(), "Submit")]').click();

// nth element
await page.locator('table tr').nth(2).click();

// Filter locators
await page.getByRole('listitem').filter({ hasText: 'Alice' }).click();