Playwright + Java · Lesson 17 of 38

0/38 done

Module 17: Locators

17. User-Facing Locators & Resilient Query Strategies

18 minlesson

Your task

Write a method getSubmitButton:

  1. Accept Page page and String buttonName.
  2. Return page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(buttonName)).

Write it in the editor, then press Check answer (Ctrl + Enter).

Best Practice Locator Hierarchy

  1. page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit"))
  2. page.getByLabel("Email Address")
  3. page.getByPlaceholder("Enter your password")
  4. page.getByText("Welcome back")
  5. page.getByTestId("checkout-btn")
java
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;

Locator submitBtn = page.getByRole(AriaRole.BUTTON,
    new Page.GetByRoleOptions().setName("Confirm Payment"));

Key Takeaways & Walkthrough Summary

Locators are the heart of reliable Playwright automation. Playwright locators are lazy and automatically resolve every time you interact with them. In this lesson, we prioritize user-facing accessibility locators like getByRole and getByLabel over fragile CSS and XPath selectors. Let's master locators!

Part of the Playwright + Java course (Playwright with Java). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What is Playwright Strict Mode?

In Playwright, if a locator matches multiple elements and you call click() or fill(), it throws a strict mode violation error, catching unintended UI ambiguities.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip