How to find elements by CSS selectors in Playwright?

You can find elements by CSS selectors in Playwright by using the locator method of the Page object. Playwright can automatically detect that a CSS selector is being passed in as an argument. Alternatively, you can prepend your CSS selector with css= 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 CSS 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 CSS selector and print it
    title = page.locator('css=title')

Related Playwright web scraping questions: