🚀 We are hiring! See open positions

How to find elements by CSS selectors in Playwright?

by Bernardas Alisauskas May 29, 2023 1 min read

The most popular way to parse HTML content in web scraping are CSS selectors which are the default way to locate elements in Playwright as well. To find elements using CSS selectors we can use page.locator() method. For example:

python
from playwright.sync_api import sync_playwright

with sync_playwright() as pw:
    browser = pw.chromium.launch(headless=False)
    context = browser.new_context(viewport={"width": 1920, "height": 1080})
    page = context.new_page()
    page.goto("https://google.com/")

    h2_element = page.locator("h2.some-class")

âš  It's possible that these commands will try to find elements before the page has fully loaded if it's a dynamic javascript page. For more see how-to-wait-for-page-to-load-in-playwright

Also see: how-to-find-elements-by-xpath-in-playwright

Scale Your Web Scraping
Anti-bot bypass, browser rendering, and rotating proxies — all in one API. Start with 1,000 free credits.
No credit card required 1,000 free API credits Anti-bot bypass included
Not ready? Get our newsletter instead.