How to find elements by XPath selectors in Playwright?

You can find elements by XPath selectors in Playwright by using the locator method of the Page object. Playwright can automatically detect that an XPath is being passed as an argument. Alternatively, you can prepend your XPath with xpath= to make sure Playwright doesn't make a wrong guess.

Here is some sample code that prints the title of ScrapingBee website by making use of XPath selectors:

from playwright import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()

    # Extract the title using XPath selector and print it
    title = page.locator('xpath=//title')

Related Playwright web scraping questions: