Back to All Questions
Question 22 of 100
Locators
Beginner
What is the importance of getByLabel locator in Playwright?
The Answer
`getByLabel` finds form elements (input, textarea, select) by their associated `<label>` text. This is the recommended way to locate form fields because it reflects how users identify fields on a form.
Deep Dive Explanation
Using getByLabel enforces accessible forms. If your label association breaks (e.g., the `for` attribute is removed), the test will fail β alerting you to an accessibility regression. This is a huge advantage over CSS selectors which would silently pass.
example.spec.ts
// HTML: <label for="email">Email Address</label><input id="email" />
await page.getByLabel('Email Address').fill('user@example.com');
// Works with aria-label too
await page.getByLabel('Search').fill('playwright');