π― Why User-Facing Locators Matter
In traditional test automation, tests often break due to implementation detailsβsuch as auto-generated CSS class names (e.g., css-1v3b9x) or brittle DOM tree XPaths (e.g., //div[2]/form/div[1]/button). Playwright recommends user-facing locators that reflect how real users and assistive screen readers perceive the page. By targeting elements using explicit ARIA roles, accessible names, form label associations, input placeholders, and image alt attributes, test suites become resilient to front-end refactoring while enforcing web accessibility standards (a11y) across your web applications.
RECOMMENDED LOCATOR PRIORITY ORDER:
1. page.get_by_role() βββΊ Locates by ARIA role & accessible name (button, link, heading, textbox).
2. page.get_by_label() βββΊ Locates form inputs by their associated <label> element text.
3. page.get_by_placeholder() βββΊ Locates input elements by their placeholder attribute text.
4. page.get_by_text() βββΊ Locates elements containing explicit non-interactive text content.
5. page.get_by_alt_text() βββΊ Locates graphical images/areas by their alt text attribute.
6. page.get_by_title() βββΊ Locates elements by their HTML title hover attribute.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
7. page.get_by_test_id() βββΊ Locates by dedicated data-testid attributes (developer contracts).
8. page.locator("css / xpath")βββΊ Fallback only when semantic or accessible markers do not exist.
get_by_role() queries elements via their semantic ARIA role and accessible name. It disambiguates between buttons, links, and headings even when they share the exact same text.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Sample form with multiple elements sharing similar labels
page.set_content("""
Customer Account Portal
""")
# 1. Target Level 1 Heading
heading = page.get_by_role("heading", name="Customer Account Portal", level=1)
expect(heading).to_be_visible()
# 2. Target Link anchor specifically (ignores button sharing the same 'Sign In' text)
nav_link = page.get_by_role("link", name="Sign In")
expect(nav_link).to_have_attribute("href", "/login")
# 3. Target Submit Button specifically
submit_btn = page.get_by_role("button", name="Sign In")
expect(submit_btn).to_be_enabled()
# 4. Target Textbox by accessible aria-label
user_input = page.get_by_role("textbox", name="Username")
user_input.fill("nikita_admin")
print("All role-based locators resolved unambiguously!")
print(f"Heading text verified: '{heading.inner_text()}'")
browser.close()
get_by_label() identifies input elements associated with a <label> via for="id" or nested labeling. It works across text inputs, checkboxes, radios, and textareas.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Standard accessible billing form
page.set_content("""
""")
# 1. Target input linked via for="user-email"
email_input = page.get_by_label("Business Email Address")
email_input.fill("support@nikita-infotech.com")
# 2. Target checkbox wrapped inside label text
terms_checkbox = page.get_by_label("I agree to the Terms of Service")
terms_checkbox.check()
# Verify states
expect(email_input).to_have_value("support@nikita-infotech.com")
expect(terms_checkbox).to_be_checked()
print("Form controls successfully located and populated via get_by_label()!")
browser.close()
get_by_placeholder() locates elements by their grayed-out placeholder attribute.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://demo.playwright.dev/todomvc/")
# Target input by placeholder prompt text
new_todo = page.get_by_placeholder("What needs to be done?")
# Assert and interact
expect(new_todo).to_be_visible()
new_todo.fill("Review User-Facing Locators Architecture")
new_todo.press("Enter")
# Verify newly added element appears in the list
todo_item = page.locator(".todo-list li").first
expect(todo_item).to_have_text("Review User-Facing Locators Architecture")
print(f"Todo input located via placeholder text: '{new_todo.get_attribute('placeholder')}'")
browser.close()
get_by_text() locates non-interactive content (paragraphs, spans, alerts, error messages). By default, it performs case-insensitive substring matching. Use exact=True for exact match.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
Order ORD-9921 has been placed successfully!
Order
""")
# 1. Substring Matching (Default: matches "Order ORD-9921...")
toast_msg = page.get_by_text("placed successfully")
expect(toast_msg).to_be_visible()
print("Substring match verified:", toast_msg.inner_text())
# 2. Exact Matching (Avoids collision with longer toast message)
exact_badge = page.get_by_text("Order", exact=True)
expect(exact_badge).to_have_class("badge")
print(f"Exact match verified: '{exact_badge.inner_text()}' (Tag: {exact_badge.evaluate('el => el.className')})")
browser.close()
alt attribute text. This verifies visual branding while ensuring screen-reader accessibility compliance.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
""")
# Locate corporate brand logo via alt text
logo = page.get_by_alt_text("Nikita Infotech Corporate Logo")
expect(logo).to_be_visible()
expect(logo).to_have_attribute("id", "brand-logo")
# Locate user avatar using substring match
avatar = page.get_by_alt_text("Profile Photo")
expect(avatar).to_be_visible()
print("Accessible images successfully located via get_by_alt_text()!")
print(f"Logo Source Attribute: '{logo.get_attribute('src')}'")
browser.close()
title attribute. get_by_title() locates these icon-only buttons reliably.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Toolbar with icon-only action buttons containing title tooltips
page.set_content("""
""")
# Locate icon buttons via their tooltip title attributes
refresh_btn = page.get_by_title("Refresh Data Stream")
export_btn = page.get_by_title("Download CSV Report")
expect(refresh_btn).to_be_visible()
expect(export_btn).to_have_attribute("id", "btn-export")
print(f"Refresh Button Located: id='{refresh_btn.get_attribute('id')}'")
print(f"Export Button Located : id='{export_btn.get_attribute('id')}'")
browser.close()
re.compile()) into locator arguments to handle dynamic order IDs, currency amounts, or fluctuating status badges.
import re
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Dynamic invoice notification banner
page.set_content("""
Confirmation: Invoice #INV-88219 has been settled.
""")
# 1. Match dynamic invoice text using Regex pattern
invoice_alert = page.get_by_text(re.compile(r"Invoice #INV-\d+"))
expect(invoice_alert).to_be_visible()
# 2. Match dynamic price button ignoring exact rupee amount
payment_button = page.get_by_role("button", name=re.compile(r"Submit Payment.*"))
expect(payment_button).to_be_enabled()
print(f"Regex Matched Alert Text : '{invoice_alert.inner_text()}'")
print(f"Regex Matched Button Text: '{payment_button.inner_text()}'")
browser.close()
get_by_test_id() as a resilient developer contract.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Complex dashboard card with data-testid attributes
page.set_content("""
βΉ 14,85,000
""")
# Locate via data-testid attribute
metric_card = page.get_by_test_id("revenue-metric-card")
metric_value = page.get_by_test_id("metric-total-revenue")
details_btn = page.get_by_test_id("btn-metric-details")
expect(metric_card).to_be_visible()
expect(metric_value).to_have_text("βΉ 14,85,000")
expect(details_btn).to_be_enabled()
print(f"Located Card by Test ID : data-testid='{metric_card.get_attribute('data-testid')}'")
print(f"Metric Value Readout : '{metric_value.inner_text()}'")
browser.close()
PLAYWRIGHT USER-FACING LOCATORS MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Locator Method β Primary Target HTML Tags β Key Parameters / Options β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β page.get_by_role() β <button>, <a>, <h1-h6>, inputβ role (str), name (str/Regex), exact, level, checked β
β page.get_by_label() β <input>, <textarea>, <select>β text (str/Regex), exact (bool) β
β page.get_by_placeholder() β <input placeholder="..."> β text (str/Regex), exact (bool) β
β page.get_by_text() β <p>, <span>, <div>, <label> β text (str/Regex), exact (bool) β
β page.get_by_alt_text() β <img alt="...">, <area> β text (str/Regex), exact (bool) β
β page.get_by_title() β Any tag with title="..." β text (str/Regex), exact (bool) β
β page.get_by_test_id() β Any tag with data-testid β test_id (str/Regex) β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β COMMON ARIA ROLES: β
β * "button" βββΊ <button>, <input type="submit">, elements with role="button" β
β * "link" βββΊ <a href="...">, elements with role="link" β
β * "heading" βββΊ <h1> through <h6>, specify level=1..6 β
β * "textbox" βββΊ <input type="text|email|password">, <textarea> β
β * "checkbox" βββΊ <input type="checkbox">, specify checked=True/False β
β * "combobox" βββΊ <select> dropdowns or custom ARIA autocomplete controls β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ