How do I find an input by its label in Playwright?
Written by Jatin Thacker, Automation Architect · Updated
This answer is one piece of Chapter 9: Locators I: What the User Sees.
- getByRole and the Accessible Name
- getByText, getByLabel, getByPlaceholder, getByTestId
- Strict Mode — One Locator, One Element
A label is what a user reads to know what a field is for, so it makes a good locator: it rarely changes unless the meaning of the field changes. Playwright's documentation recommends getByLabel() for locating form fields.
The association is what matters, not where the text sits on screen. The fulfilment form's first step shows three different wirings, and getByLabel() handles all of them:
- Customer name uses
<label for="cust-name">pointing at the input's id. - Purchase order number is a
<label>element wrapped around the input, with noforattribute at all. - GSTIN has no visible label. It has
aria-label="GSTIN"on the input.
The test fills each one through its label, then checks the value landed in the right input with toHaveValue().
Like the other getBy methods, the match is a case-insensitive substring by default. Pass { exact: true } when one label is part of another. If getByLabel() finds nothing for a label you can see, the label is probably not associated with the input. That is a real accessibility defect worth reporting, not just a locator problem.
import { test, expect } from '@playwright/test';
test('getByLabel finds inputs however the label is wired', async ({ page }) => {
await page.goto('/fulfilment.html?mock=static&seed=42&autologin=1');
// <label for="cust-name"> pointing at the input's id
await page.getByLabel('Customer name').fill('Meera Pillai');
// <label> wrapped around the input, with no for/id pair
await page.getByLabel('Purchase order number').fill('PO-7781');
// no visible label at all, only aria-label="GSTIN"
await page.getByLabel('GSTIN').fill('27AAPFU0939F1ZV');
await expect(page.getByTestId('cust-name')).toHaveValue('Meera Pillai');
await expect(page.getByTestId('cust-po')).toHaveValue('PO-7781');
await expect(page.getByTestId('cust-gstin')).toHaveValue('27AAPFU0939F1ZV');
});1 passed (1.9s)
aria-label="GSTIN" and no <label> element anywhere near it. What does page.getByLabel('GSTIN') do?Practised in the full course: the drill Customer name.
See the chapterRelated questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free