π CSS & XPath in the Playwright Engine
While accessibility-first locators are preferred for standard UI elements, modern enterprise web applications feature dynamic data grids, complex canvas elements, legacy table hierarchies, and custom SVG diagrams where semantic roles do not exist. Playwright elevates standard CSS and XPath by eliminating manual engine prefixes (automatically detecting // or xpath=), introducing non-standard pseudo-classes like :has-text() and :visible, piercing open Shadow DOM trees transparently, and auto-waiting on element stability before executing actions.
// or .. defaults to the XPath engine, while other strings default to CSS. Explicit prefixes like css= and xpath= can also be specified.
SELECTOR ENGINE PREFIXES & AUTO-DETECTION:
1. Standard CSS Selector:
page.locator("button.checkout-btn")
page.locator("css=button.checkout-btn")
2. Implicit XPath (Starts with // or ..):
page.locator("//button[contains(@class, 'checkout-btn')]")
page.locator("xpath=//button[contains(@class, 'checkout-btn')]")
3. Text Selector Engines:
page.locator("text=Submit Payment")
4. Playwright Enhanced CSS Pseudo-classes:
page.locator("div.card:has-text('Order #1042')")
page.locator("button:visible")
page.locator("tr:has(button.delete-btn)")
id="input-card_9821a_temp"). CSS attribute operators match dynamic tokens reliably using ^= (starts with), $= (ends with), and *= (contains).
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("""
""")
# 1. Starts-with operator (^=): Target input by dynamic ID prefix
email_field = page.locator("input[id^='user-email-']")
email_field.fill("automation@nikita-infotech.com")
# 2. Contains operator (*=): Target phone input containing substring
phone_field = page.locator("input[id*='phone']")
phone_field.fill("9876543210")
# 3. Ends-with operator ($=): Target document download anchor ending in .pdf
pdf_link = page.locator("a[href$='.pdf']")
expect(email_field).to_have_value("automation@nikita-infotech.com")
expect(phone_field).to_have_value("9876543210")
expect(pdf_link).to_have_attribute("href", "/downloads/monthly_report_2026.pdf")
print("All dynamic CSS attribute wildcards resolved successfully!")
browser.close()
:has-text() and :visible to locate containers based on internal text.
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("""
Total Orders
1,420
Active Incidents
3
""")
# Target specific metric card containing 'Active Incidents' and click its child button
incident_card = page.locator(".metric-card:has-text('Active Incidents')")
inspect_btn = incident_card.locator("button.view-btn")
expect(incident_card).to_be_visible()
expect(inspect_btn).to_be_enabled()
# Read verified incident count specifically within the isolated card scope
count_val = incident_card.locator(".count").inner_text()
print(f"Target Container Located via :has-text() | Incidents: {count_val}")
browser.close()
:has() pseudo-class selects parent elements that contain a descendant matching an inner selector. This enables targeting entire rows or cards based on inner badges or icons.
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("""
ORD-101
Shipped
ORD-102
Failed Payment
""")
# Select the table row (tr) that specifically contains a descendant with class '.pending'
failed_row = page.locator("tr.order-row:has(.badge.pending)")
# Click retry button strictly scoped inside that failed row
retry_button = failed_row.locator("button.action-btn")
expect(failed_row).to_contain_text("ORD-102")
expect(retry_button).to_have_text("Retry")
print(f"Target Row Identified: '{failed_row.locator('td').first.inner_text()}'")
print(f"Associated Action Button: '{retry_button.inner_text()}'")
browser.close()
ancestor::.
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("""
Company Tax GSTIN:
27AAAAA0000A1Z5
""")
# 1. XPath following-sibling: Locate span immediately following the label title
gstin_value = page.locator("//span[text()='Company Tax GSTIN:']/following-sibling::span")
expect(gstin_value).to_have_text("27AAAAA0000A1Z5")
# 2. XPath ancestor: Walk up to parent container row and locate action button
copy_button = page.locator("//span[text()='Company Tax GSTIN:']/ancestor::div[contains(@class, 'row')]//button")
expect(copy_button).to_be_visible()
print(f"XPath Sibling Traversal Extracted: '{gstin_value.inner_text()}'")
print(f"XPath Ancestor Discovered Button : '{copy_button.inner_text()}'")
browser.close()
contains(), normalize-space(), and starts-with() query nodes with whitespace formatting or composite internal strings.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# HTML containing extra whitespaces and newlines
page.set_content("""
Status: System maintenance scheduled for Sunday at 02:00 AM IST.
Renew Subscription License
""")
# 1. normalize-space() removes excess whitespace/newlines before comparison
status_p = page.locator("//p[contains(normalize-space(.), 'System maintenance scheduled')]")
expect(status_p).to_be_visible()
# 2. Nested anchor text lookup
renew_link = page.locator("//a[.//span[text()='Renew Subscription License']]")
expect(renew_link).to_have_attribute("href", "/renew")
print("Normalized XPath string matches evaluated cleanly!")
print(f"Extracted Alert: '{status_p.inner_text().strip()}'")
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("""
Invoice ID Date Amount Action
INV-2026-01 10 Oct 2026 βΉ 12,500
INV-2026-02 15 Oct 2026 βΉ 45,000
INV-2026-03 22 Oct 2026 βΉ 8,900
""")
# Target the specific row containing 'INV-2026-02', then select its PDF download button
target_invoice = "INV-2026-02"
invoice_button = page.locator(f"//table[@id='billing-ledger']//tr[td[text()='{target_invoice}']]//button")
expect(invoice_button).to_be_visible()
expect(invoice_button).to_have_attribute("id", "btn-2")
print(f"Target Invoice: {target_invoice}")
print(f"Located Action Button ID via Relational XPath: '{invoice_button.get_attribute('id')}'")
browser.close()
//svg fail in standard HTML parsers without the local-name() function. Playwright natively supports standard CSS and XML namespaces for SVGs.
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("""
3
""")
# 1. CSS Selector targeting SVG directly
svg_via_css = page.locator("svg.cart-icon path.wheel-path")
expect(svg_via_css).to_be_attached()
# 2. XPath utilizing local-name() to bypass XML namespace collisions
svg_via_xpath = page.locator("//*[local-name()='svg' and @class='cart-icon']/*[local-name()='path']")
expect(svg_via_xpath).to_be_attached()
print("SVG paths queried and verified using both CSS and XPath local-name()!")
print(f"SVG Class Name: '{page.locator('svg').get_attribute('class')}'")
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 with nested custom Web Component
page.set_content("""
""")
# Playwright CSS pierces Shadow DOM automatically!
shadow_input = page.locator("custom-input-card input.internal-input")
shadow_button = page.locator("custom-input-card button.internal-btn")
shadow_input.fill("SEC-AUTH-TOKEN-771")
expect(shadow_input).to_have_value("SEC-AUTH-TOKEN-771")
expect(shadow_button).to_have_text("Confirm")
print("Successfully pierced Web Component shadow boundary using standard CSS selector!")
print(f"Target Placeholder: '{shadow_input.get_attribute('placeholder')}'")
browser.close()
CSS VS. XPATH IN PLAYWRIGHT PYTHON:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββ¬βββββββββββββββββββββββββ
β Feature / Capability β CSS Selectors β XPath Expressions β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌβββββββββββββββββββββββββ€
β Execution Speed β Extremely Fast (Native)β Fast (Browser Engine) β
β Shadow DOM Piercing β β Automatic & Seamless β β Cannot cross Shadow β
β Text Filtering β β Via :has-text() β β Via text() / containsβ
β Parent Element Traversal β β Via :has() β β Via /.. or ancestor::β
β Sibling Traversal β β Adjacent / General β β following / precedingβ
β Complex Logic (AND / OR) β Moderate β Advanced boolean logic β
β Syntactical Readability β High, concise, clean β Verbose for deep trees β
β Maintenance Overhead β Lower β Higher if hardcoded β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ΄βββββββββββββββββββββββββ