LOCATOR FILTERING & CHAINING IN PYTHON

Master modular element narrowing in Playwright with Python: sequential locator chaining, inner locator scoping, has_text and has predicate filtering, index selection (nth, first, last), list iteration, and strict mode disambiguation.

🔗 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.

1. Chaining Locators: Progressive DOM Scope Narrowing
Chaining connects sequential locators together using dot notation. The child locator searches strictly inside the subtree matched by the parent locator, preventing accidental element collisions elsewhere on the page.
Conceptual Model & 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")
Architectural Advantage: Prevents element ambiguity errors and makes Page Object Models modular and easy to maintain.
Real-Time Example 1: Basic Locator Chaining within Modal Dialogs
Isolate form fields and buttons rendered inside active popups or modal overlays, ensuring actions do not target identical hidden elements residing on the background page.
Python (Modal Scope Chaining)
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("""
        
""") # 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()
Output: Modal Container Title: 'Confirm Deletion' Scoped Action Button : 'Delete Permanently'
Real-Time Example 2: filter(has_text=...) - Row Filtering by Visible Content
Use filter(has_text=...) to isolate a specific parent row or container based on visible substring or exact text, without writing brittle, hardcoded XPath hierarchies.
Python (filter has_text Implementation)
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()
Output: Target Row Scoped: 'Pooja Patil' Assigned Role : 'Administrator' Action Button : 'Promote'
Real-Time Example 3: filter(has=...) - Filtering by Descendant Locator
Filter containers based on whether they contain a specific descendant element (e.g., finding the table row that contains a verified status badge or an unchecked checkbox).
Python (filter has Descendant Locator)
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()
Output: Located Card Title : 'Industrial Sensor Hub' Located Button Text: 'Order Now'
Real-Time Example 4: Combining has_text and has Filters
Combine multiple filter criteria in sequence to create ultra-specific locator predicates, guaranteeing exact matches across dynamic enterprise dashboards.
Python (Composite Chained Filters)
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
INV-102 Cloud Infrastructure PENDING
INV-103 Cloud Infrastructure
""") # 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()
Output: Composite filter successfully matched single row: Invoice ID : 'INV-101' Button Text: 'Pay Now'
Real-Time Example 5: Positional Selection (first, last, nth)
When multiple identical elements exist and cannot be distinguished by text, use index accessors: .first, .last, or .nth(index) (zero-indexed).
Python (Positional Element Selection)
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()
Output: Tasks Count: 4 First Task : 'Sprint Planning' Nth(2) Task: 'Performance Testing' Last Task : 'Production Release'
Real-Time Example 6: Iterating through Matched Locators (.all())
Extract data or validate conditions across lists of matching elements using locator.all(). This returns a Python list of individual Locator instances for standard iteration.
Python (Iterating with locator.all)
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()
Output: Discovered 3 Subscription Plans: [1] Starter -> ₹ 999 [2] Professional -> ₹ 2,499 [3] Enterprise -> ₹ 7,999
Real-Time Example 7: Strict Mode Disambiguation & Error Resolution
Playwright enforces Strict Mode by default: attempting an action on a locator that matches multiple elements raises an error. Use filtering or .first to resolve ambiguities deterministically.
Python (Resolving Strict Mode Violations)
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()
Output: Caught Strict Mode Exception: Error: strict mode violation: locator("button.action-btn") resolved to 2 elements: Resolution A (.first) succeeded! Resolution B (.nth) succeeded!
Real-Time Example 8: Component-Driven Page Object Model Scoping
In enterprise Page Object Models, encapsulate child components (e.g., table rows or product cards) as reusable sub-objects initialized with a scoped Locator root.
Python (Component Scoping Pattern)
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()
Output: Component Object Model Interaction Successful: Title: 'Playwright Pro Frameworks' Price: '₹ 1,199'
Real-Time Example 9: Locator Filtering & Chaining Reference Matrix
A comprehensive reference summary of methods and arguments used for narrowing, filtering, and navigating locator collections in Playwright Python.
Filtering & Chaining Reference Matrix
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. │
└──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┘
Engineering Best Practice: Prefer chaining and filter(has_text=...) over complex XPath ancestor queries to keep test suites readable, robust, and refactoring-safe.