🔗 What are Locator Chaining & Filtering?
In enterprise web applications, real-world user interfaces rarely present elements in isolation. Instead, items are repeated across tables, product cards, list rows, and modal dialogs. Writing long, monolithic XPath or CSS queries to locate an action button inside a specific row creates fragile test code. Playwright Locator Chaining and Filtering allows automation engineers to narrow search scopes progressively. By composing locators with locator.locator() and applying fine-grained criteria via locator.filter(has_text=..., has=...), scripts isolate dynamic components with clean, self-documenting syntax.
DOM SCOPE NARROWING FLOW:
┌────────────────────────────────────────────────────────┐
│ page.locator("#shopping-cart") │ <-- Scope: Entire Cart Panel
│ └── .locator("li.cart-item") │ <-- Scope: Individual Cart Rows
│ └── .get_by_role("button", name="Delete") │ <-- Scope: Specific Delete Action
└────────────────────────────────────────────────────────┘
# Playwright Python Chaining Patterns:
# 1. Direct Chained Call
page.locator("#shopping-cart").locator("li.cart-item").get_by_role("button", name="Delete").click()
# 2. Reusable Modular Scope (Base Component Pattern)
cart_panel = page.locator("#shopping-cart")
checkout_button = cart_panel.get_by_role("button", name="Proceed to Checkout")
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("""
Confirm Deletion
Are you sure you want to delete this invoice?
""")
# Scope strictly inside the modal dialog container
modal = page.locator("#confirm-modal")
modal_save_btn = modal.locator(".primary-btn")
modal_delete_btn = modal.locator(".danger-btn")
expect(modal).to_be_visible()
expect(modal_save_btn).to_be_visible()
expect(modal_delete_btn).to_have_text("Delete Permanently")
print(f"Modal Container Title: '{modal.locator('h2').inner_text()}'")
print(f"Scoped Action Button : '{modal_delete_btn.inner_text()}'")
browser.close()
filter(has_text=...) to isolate a specific parent row or container based on visible substring or exact text, without writing brittle, hardcoded XPath hierarchies.
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("""
-
Aarav Sharma
Staff
-
Pooja Patil
Administrator
""")
# Target the user row specifically containing the name 'Pooja Patil'
target_row = page.locator(".user-row").filter(has_text="Pooja Patil")
action_button = target_row.locator("button.status-btn")
expect(target_row).to_be_visible()
expect(action_button).to_have_text("Promote")
print(f"Target Row Scoped: '{target_row.locator('.name').inner_text()}'")
print(f"Assigned Role : '{target_row.locator('.role').inner_text()}'")
print(f"Action Button : '{action_button.inner_text()}'")
browser.close()
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("""
Industrial Sensor Hub
Available
High-Speed Optic Relay
Backorder
""")
# Filter cards by checking for the presence of a specific inner badge locator
in_stock_card = page.locator(".card").filter(has=page.locator("span.in-stock"))
order_button = in_stock_card.locator("button")
expect(in_stock_card).to_have_attribute("id", "card-1")
expect(order_button).to_have_text("Order Now")
print(f"Located Card Title : '{in_stock_card.locator('h3').inner_text()}'")
print(f"Located Button Text: '{order_button.inner_text()}'")
browser.close()
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("""
INV-101
Consulting Services
PAID
INV-102
Cloud Infrastructure
PENDING
INV-103
Cloud Infrastructure
PAID
""")
# Target row matching BOTH 'Cloud Infrastructure' text AND containing a 'span.pending' badge
pending_cloud_row = (
page.locator(".ledger-row")
.filter(has_text="Cloud Infrastructure")
.filter(has=page.locator("span.pending"))
)
action_btn = pending_cloud_row.locator("button")
expect(pending_cloud_row).to_contain_text("INV-102")
expect(action_btn).to_have_text("Pay Now")
print("Composite filter successfully matched single row:")
print(f" Invoice ID : '{pending_cloud_row.locator('td').first.inner_text()}'")
print(f" Button Text: '{action_btn.inner_text()}'")
browser.close()
.first, .last, or .nth(index) (zero-indexed).
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("""
- Sprint Planning
- API Schema Review
- Performance Testing
- Production Release
""")
tasks = page.locator(".task-list li.task")
# 1. First element
first_task = tasks.first
expect(first_task).to_have_text("Sprint Planning")
# 2. Last element
last_task = tasks.last
expect(last_task).to_have_text("Production Release")
# 3. Nth element (zero-indexed: 2 = third element)
third_task = tasks.nth(2)
expect(third_task).to_have_text("Performance Testing")
print(f"Tasks Count: {tasks.count()}")
print(f" First Task : '{first_task.inner_text()}'")
print(f" Nth(2) Task: '{third_task.inner_text()}'")
print(f" Last Task : '{last_task.inner_text()}'")
browser.close()
locator.all(). This returns a Python list of individual Locator instances for standard iteration.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
Starter₹ 999
Professional₹ 2,499
Enterprise₹ 7,999
""")
# Extract all matching elements into a Python list of Locators
plans = page.locator(".pricing-matrix .plan").all()
print(f"Discovered {len(plans)} Subscription Plans:")
extracted_data = []
for idx, plan in enumerate(plans, 1):
title = plan.locator(".title").inner_text()
price = plan.locator(".price").inner_text()
extracted_data.append({"tier": title, "price": price})
print(f" [{idx}] {title:15s} -> {price}")
browser.close()
.first to resolve ambiguities deterministically.
from playwright.sync_api import sync_playwright, Error as PlaywrightError
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
""")
# 1. Ambiguous query triggers Strict Mode violation
ambiguous_locator = page.locator("button.action-btn")
try:
ambiguous_locator.click()
except PlaywrightError as err:
print("Caught Strict Mode Exception:")
print(" ", str(err).splitlines()[0])
# 2. RESOLUTION A: Narrow scope using positional indexing
ambiguous_locator.first.click()
print("Resolution A (.first) succeeded!")
# 3. RESOLUTION B: Disambiguate using parent scoping
page.locator(".toolbar").locator("button").nth(1).click()
print("Resolution B (.nth) succeeded!")
browser.close()
from playwright.sync_api import Locator, sync_playwright, expect
class ProductCardComponent:
"""Encapsulates locators and actions for a single product card."""
def __init__(self, root: Locator):
self.root = root
self.title = root.locator("h4.product-title")
self.price = root.locator("span.price-tag")
self.add_btn = root.get_by_role("button", name="Add to Cart")
def add_to_cart(self):
self.add_btn.click()
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
Python Automation Playbook
₹ 799
Playwright Pro Frameworks
₹ 1,199
""")
# Target specific card using filter, then bind to component object
card_locator = page.locator(".card").filter(has_text="Playwright Pro Frameworks")
product_card = ProductCardComponent(card_locator)
expect(product_card.title).to_have_text("Playwright Pro Frameworks")
expect(product_card.price).to_have_text("₹ 1,199")
product_card.add_to_cart()
print("Component Object Model Interaction Successful:")
print(f" Title: '{product_card.title.inner_text()}'")
print(f" Price: '{product_card.price.inner_text()}'")
browser.close()
PLAYWRIGHT FILTERING & CHAINING METHODS MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Method / Operation │ Arguments │ Primary Description / Use Case │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ locator.locator() │ selector: str │ Narrows scope to descendants matching the selector. │
│ locator.filter(has_text=...) │ text: str / Pattern (Regex) │ Filters matches to those containing specified text. │
│ locator.filter(has=...) │ locator: Locator │ Filters matches to those containing inner descendant. │
│ locator.filter(has_not_text) │ text: str / Pattern (Regex) │ Filters matches to those NOT containing specified text. │
│ locator.filter(has_not=...) │ locator: Locator │ Filters matches to those NOT containing descendant. │
│ locator.first │ Property │ Selects the first element from the matched collection. │
│ locator.last │ Property │ Selects the final element from the matched collection. │
│ locator.nth(index) │ index: int (zero-indexed) │ Selects element at index N (e.g. nth(0) is first). │
│ locator.count() │ None (returns int) │ Counts total elements currently matching the locator. │
│ locator.all() │ None (returns List[Locator]) │ Returns all matched elements as a standard Python list. │
└──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┘