How to find elements by XPath selectors in Playwright?

A Playwright XPath selector finds an element by its position, tag, attributes, or relationship to other elements in the page's HTML. To use XPath in Playwright, pass the selector to page.locator(). Add the xpath= prefix or begin the selector with //. The method returns a locator that you can use to read text, click the element, or fill a field.

The example below uses a Playwright XPath locator to find the <title> element on the ScrapingBee homepage and print its text.

Before running the code, install Playwright and its browser binaries:

pip install playwright
playwright install
from playwright.sync_api import sync_playwright

with sync_playwright() as playwright:
    # Launch Chromium in headless mode
    browser = playwright.chromium.launch(headless=True)

    # Open the target page
    page = browser.new_page()
    page.goto(
        "https://www.scrapingbee.com/",
        wait_until="domcontentloaded",
    )

    # Find the title element using XPath
    title = page.locator("xpath=//title")

    # Print the element text
    print(title.text_content())
    browser.close()

Our output is the current title of the ScrapingBee homepage:

Terminal output showing the ScrapingBee homepage title read with a Playwright XPath locator

The xpath= prefix tells Playwright that the value is an XPath selector:

title = page.locator("xpath=//title")

You can also leave out the prefix when the selector starts with //, as shown below:

title = page.locator("//title")

Playwright detects both forms as XPath. Using xpath= makes it easier to identify the selector when reading code.

To find a page element by an attribute, replace the title locator in the script above with the following:

pricing_link = page.locator(
    "xpath=//a[contains(@href, '/pricing')]"
).first
print(pricing_link.text_content())

The homepage links to the pricing page more than once, so .first picks the first match. And the output is the element pricing as seen here:

Terminal output showing the Pricing link text matched by a Playwright XPath attribute selector

Related Playwright web scraping questions: