How to Use Playwright Java getByLabel Locator with Examples

How to use getByLabel locator in Playwright Java with code and form field example

When writing automated UI tests, finding elements precisely is essential. Playwright Java getByLabel helps you locate form controls using their visible labels, making your tests more readable, reliable, and easier to maintain. In this guide, you’ll learn how to use the getByLabel locator in Playwright Java, explore practical examples, understand when to use it, and discover how it compares with other Playwright Java locators such as getByRole, getByText, and getByPlaceholder.

What is getByLabel in Playwright Java?

In Playwright Java, locators are powerful tools used to find and interact with elements on a webpage. Playwright locators are designed to make test scripts cleaner, more stable, and closer to how real users interact with web applications. Instead of relying on fragile selectors like CSS or XPath, Playwright provides human-readable locators such as getByRole, getByText, getByPlaceholder, and getByLabel.

The getByLabel locator in Playwright Java is used to identify and interact with form controls based on their visible text label. For example, if a web form has a label like “Email address” linked to an input field, you can use page.getByLabel("Email address") to locate and fill that input. This approach makes tests more natural and easier to understand since it mirrors how users visually recognize elements on a page.

Playwright introduced this locator to improve test readability and maintainability. Traditional CSS Selectors or XPath locators often break when UI structures change, but label-based locators remain stable as long as the visible label stays consistent. This makes your automation code less prone to maintenance issues and easier to review or update.

The main difference between label-based and attribute-based locators is how they target elements. Label-based locators, like getByLabel, rely on visible text associated with an element, such as the <label> tag linked to an input. Attribute-based locators, on the other hand, depend on HTML attributes like id, name, or class. While attribute-based locators can be useful in certain cases, they are often less intuitive and more sensitive to DOM structure changes. In contrast, using label-based locators aligns your tests with the user’s perspective, making them more robust and readable.

2. Why Use getByLabel Locator in Playwright Java

The getByLabel locator in Playwright Java offers several advantages when working with form-based applications. It allows testers to target elements using the same labels visible to end users, which makes tests both intuitive and closer to real user interactions.

Benefits of Using getByLabel for Form Elements

Using getByLabel simplifies the process of identifying input fields, dropdowns, checkboxes, and radio buttons. Since it directly connects to the visible label text, you don’t need to depend on fragile selectors like IDs or class names that often change during development. As long as the label remains consistent, your test will continue to work without requiring updates. This helps reduce test maintenance and makes your automation scripts more stable over time.

Readability and Maintainability Advantages

Tests that use getByLabel are easier to read and understand, even for those who didn’t write the original code. Instead of reading complex CSS selectors, a statement like page.getByLabel("Email") immediately conveys its purpose. This improves collaboration between developers, testers, and non-technical stakeholders who review test scripts. It also makes debugging simpler, as you can quickly identify which element each line of code refers to.

Real-World Testing Scenarios

The getByLabel locator is especially useful when automating forms and input-based workflows. Common examples include:

  • Login or registration forms: Filling fields like “Username”, “Email”, or “Password”.
  • Checkbox interactions: Selecting or verifying options such as “Remember me” or “I agree to the terms”.
  • Radio button selections: Choosing gender, subscription type, or payment method.
  • Search forms: Entering text into labeled fields without relying on internal attributes.

In all these scenarios, Playwright getByLabel for Java provides a cleaner, user-focused way to locate elements, leading to more maintainable and human-readable test automation.

How to Use getByLabel in Playwright Java

Basic Syntax and Usage

The getByLabel locator helps you identify form elements based on their visible label text. This makes your test scripts easier to read and more stable compared to using CSS or XPath selectors.

Here’s the basic syntax for using getByLabel in Playwright Java:

page.getByLabel("Label Text");

This method finds the element associated with the specified label and returns a locator object. You can then perform actions like fill(), click(), or check() on it.

Step-by-Step Explanation with Code

Let’s understand this with an example. Suppose you have the following HTML form:

<form>
  <label for="email">Email Address</label>
  <input type="email" id="email" />
</form>
Email Address label and input textbox highlighted in Chrome DevTools showing HTML for Playwright Java getByLabel example
Email Address label and input field highlighted in Chrome DevTools for Playwright Java getByLabel locator example

You can locate and fill the input field using its label text:

page.getByLabel("Email Address").fill("test@example.com");

Explanation:

  • getByLabel(“Email Address”) locates the input field linked to the label “Email Address”.
  • The fill() method enters text into that field.
  • You don’t need to depend on the element’s id or class attributes, making your test code easier to maintain.

getByLabel with Java Example (for Input Fields)

Here’s a complete example showing how to use the getByLabel locator in Playwright Java to interact with input fields:

We will use a local HTML file for this test, and you can download it from here.

package com.example.test;

import java.nio.file.Paths;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;

public class GetByLabelExample {
	public static void main(String[] args) {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
			Page page = browser.newPage();

			// Load the local HTML file
			page.navigate(Paths.get("D:\\getByLabel.html").toUri().toString());

			// Locate input fields using labels
			page.getByLabel("Full Name").fill("ABC XYZ");
			page.getByLabel("Email Address").fill("abc.xyz@youremail.com");
			page.getByLabel("Password").fill("MySecurePassword123");

			// Submit the form
			page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit")).click();

			System.out.println("Form submitted successfully.");

			browser.close();
		}
	}
}

This code demonstrates how to fill form fields using their visible labels. Even if the HTML structure changes, the test remains valid as long as the labels are consistent.

How Playwright Maps Labels to HTML Elements Automatically

Playwright automatically understands the relationship between labels and form controls using standard HTML rules:

  • Explicit association: when a <label> uses the for attribute to reference an input’s id:
Password label with input text field showing explicit label association in Playwright Java getByLabel example
Password label with input field demonstrating explicit label association for Playwright Java getByLabel locator
<label for="password">Password</label>
<input id="password" />
  • Implicit association: when the input field is placed inside the tag:
Full Name label with input text field showing Implicit label association in Playwright Java getByLabel example
Full Name label with input field demonstrating Implicit label association for Playwright Java getByLabel locator
<label for="fullname">Full Name
    <input type="text" id="fullname" name="fullname">
</label>

Thanks to this mapping, Playwright Java getByLabel works consistently across different HTML structures. It ensures your locators are human-readable, reliable, and aligned with how users actually interact with web forms.

Practical Examples of getByLabel Locator

The getByLabel locator in Playwright Java helps you find form elements associated with a tag, making your tests more reliable and readable.

Let’s look at a few practical examples.

getByLabel for Text Input Example

In this example, we will locate and fill text fields such as Full Name, Email Address, and Password using the getByLabel locator.

Code Example

// Locate input fields using labels
page.getByLabel("Full Name").fill("ABC XYZ");
page.getByLabel("Email Address").fill("abc.xyz@youremail.com");
page.getByLabel("Password").fill("MySecurePassword123");

// Submit the form
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit")).click();

Explanation

  • getByLabel(“Full Name”) automatically finds the input field associated with that label.
  • This makes your tests more human-readable and less dependent on HTML structure.

Playwright Java getByLabel Checkbox Example

You can also use getByLabel to interact with checkboxes linked to labels.

Code Example

// Select a checkbox
page.getByLabel("I agree to the Terms and Conditions").check();

// Verify if checkbox is selected
boolean isChecked = page.getByLabel("I agree to the Terms and Conditions").isChecked();
System.out.println("Checkbox selected: " + isChecked);

Explanation

  • The check() method selects the checkbox.
  • You can verify the state using isChecked() for assertions.

Playwright Java getByLabel Regex Example

If your label text is dynamic or partially changes, you can use regular expressions to match it flexibly.

Code Example

// Match label using partial text or dynamic content
page.getByLabel(Pattern.compile("Email.*")).fill("regex.user@example.com");

Explanation

  • The above regex Email.* matches labels like “Email Address” or “Email ID”.
  • This is useful when labels differ slightly across environments or versions.

getByLabel with Multiple Form Elements

The getByLabel locator also works with radio buttons, dropdowns, and other labeled form controls.

Code Example

// Select a first gender radio button having male label name.
page.getByLabel("Male").nth(0).check();

// Select an option from dropdown
page.getByLabel("Country").selectOption("USA");

// Fill text field again for demonstration
page.getByLabel("Full Name").fill("Jane Doe");

// Submit the form
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit")).click();

Explanation

  • Works seamlessly for multiple labeled elements like radio buttons, checkboxes, and dropdowns.
  • Keeps your locators clean and resilient to HTML structure changes.

Comparing getByLabel with Other Playwright Locators

Playwright provides different types of locators to help testers interact with web elements more efficiently. Each locator serves a unique purpose depending on how the element is identified in the DOM. Understanding when to use getByLabel, getByRole, getByText, or getByPlaceholder can help you write cleaner and more reliable Playwright Java tests.

Playwright getByRole vs getByLabel – when to use which

getByRole locates elements based on their ARIA roles, such as button, link, or textbox. It’s perfect for identifying elements with clear semantic roles.

On the other hand, getByLabel is best suited for form elements like input fields, checkboxes, and radio buttons that are explicitly linked to a visible label.

Use getByLabel when testing forms or inputs where accessibility labels are defined, and use getByRole for general UI components like buttons or navigation links.

Playwright getByText vs getByLabel – difference in targeting text elements

getByText locates elements purely by their visible text content. It’s ideal for elements like spans, divs, or buttons where the text itself is the identifier.

getByLabel, however, targets input-related elements associated with a tag. While both rely on visible text, getByLabel maps text to an input’s associated label, making it more precise for form-based testing.

Playwright getByPlaceholder – use cases for input placeholders

getByPlaceholder is used to locate input fields based on their placeholder attribute. This is useful when a field lacks a label but includes placeholder text, such as “Enter your email.”

However, placeholders are not always accessible, so using getByLabel is still the preferred approach when available.

Comparison Table for Quick Understanding

LocatorBest ForExample ElementWhen to Use
getByLabelForm fieldsInput, checkboxWhen labels are linked
getByRoleButtons, linksAccessible elementsFor semantic roles
getByTextText-based elementsButtons, spansWhen visible text is key
getByPlaceholderInput fieldsTextboxesWhen placeholder text exists

Complete Example: Playwright Java getByLabel Test Script

Now that you’ve learned how the getByLabel locator works, let’s bring everything together into a complete, runnable example. We’ll use the same local HTML file (getByLabel.html) you created earlier. This script demonstrates form automation using Playwright Java getByLabel, including setup, execution, and teardown.

Full Working Java Example

package com.example.test;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;

public class GetByLabelExample {
	public static void main(String[] args) {
		// Step 1: Launch Playwright and create a browser instance
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

			// Step 2: Create a new browser context and page
			BrowserContext context = browser.newContext();
			Page page = context.newPage();

			// Step 3: Navigate to the local HTML file
			// Update file path according to your local system
			page.navigate("file:///D:/getByLabel.html");

			// Step 4: Fill out text fields using getByLabel
			page.getByLabel("Full Name").fill("John Doe");
			page.getByLabel("Email Address").fill("john.doe@example.com");
			page.getByLabel("Password").fill("MySecurePassword123");

			// Step 5: Select checkbox and radio button using getByLabel
			page.getByLabel("Male").nth(0).check();
			page.getByLabel("I agree to the Terms and Conditions").check();

			// Step 6: Click the Submit button using getByRole
			page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit")).click();

			// Step 7: Wait to see result and close browser
			page.waitForTimeout(2000);
			System.out.println("Test completed successfully.");
			browser.close();
		}
	}
}
Explanation of Each Step
  • Playwright setup: Initializes Playwright and launches a Chromium browser. The browser runs in visible (non-headless) mode, allowing you to observe interactions.
  • Navigation to local HTML file: The page.navigate() method opens your getByLabel.html file. Ensure the file path is correct for your machine.
  • Using getByLabel to fill inputs: Each input field is identified by its visible label text, such as “Full Name” or “Email Address”. This makes the test highly readable.
  • Interacting with checkboxes and radio buttons: You can use the same getByLabel() method to select or verify checkboxes and radio buttons linked to their respective labels.
  • Clicking the Submit button: The getByRole() method locates the Submit button based on its ARIA role and visible name, demonstrating a clean combination of locators.
  • Closing the browser: After form submission, Playwright waits briefly to show the alert and then closes the browser session.
Example Output and Test Result

When you run the script:

  • The browser opens your local form.
  • All text fields are filled with the specified values.
  • “I agree to the Terms and Conditions” and the “Male” radio button is selected.
  • The form is submitted, and an alert appears saying:
Form submitted successfully!

After a brief pause, the browser window closes automatically, indicating your Playwright Java getByLabel test executed successfully.

Conclusion

The Playwright Java getByLabel locator offers a clean, readable, and reliable way to identify form elements based on their associated labels. By using this locator, your test scripts become easier to understand and maintain, especially when working with input fields, checkboxes, or radio buttons that follow accessible HTML practices.

You should prefer getByLabel whenever your form elements are correctly linked with <label> tags. It helps reduce dependency on fragile selectors like CSS or XPath and improves test stability. However, for elements without labels, Playwright provides other locators such as getByRole, getByText, and getByPlaceholder, each serving a specific purpose.

In summary, Playwright Java getByLabel enhances the overall readability and maintainability of UI tests. Experiment with different locator strategies to build more robust, reliable, and future-proof Playwright automation scripts.

author avatar
Aravind QA Automation Engineer & Technical Blogger
Aravind is a QA Automation Engineer and technical blogger specializing in Playwright, Selenium, and AI in software testing. He shares practical tutorials to help QA professionals improve their automation skills.
Stay Updated with New Articles
Get the latest tutorials and insights delivered to your inbox.

Leave a Reply

Your email address will not be published. Required fields are marked *