How to wait for page to load in Playwright?

When scraping dynamic web pages with Playwright and Python we need to wait for the page to fully load before we retrieve the page source. Using Playwright's wait_for_selector() method we can wait for a specific element to appear on the page which indicates that the web page has fully loaded and then we can grab the page source:

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

    # go to url
    page.goto("https://twitch.tv/directory/game/Art")
    # wait for element to appear on the page:
    page.wait_for_selector("div[data-target=directory-first-item]")
    # get HTML
    print(page.content())
Question tagged: Playwright, Python

Related Posts

How to Scrape Google Maps

We'll take a look at to find businesses through Google Maps search system and how to scrape their details using either Selenium, Playwright or ScrapFly's javascript rendering feature - all of that in Python.

How to Scrape Dynamic Websites Using Headless Web Browsers

Introduction to using web automation tools such as Puppeteer, Playwright, Selenium and ScrapFly to render dynamic websites for web scraping