Scrape JavaScript-Rendered Websites with Playwright: Waits, Infinite Scroll, and Downloads
playwrightjavascript-renderingbrowser-automationinfinite-scrollweb-scraping

Scrape JavaScript-Rendered Websites with Playwright: Waits, Infinite Scroll, and Downloads

sscraper.page Editorial Team
2026-12-05
8 min read

A practical Playwright checklist for scraping JavaScript-rendered pages, handling waits, infinite scroll, downloads, screenshots, and cleanup.

When a direct HTTP request returns an almost empty HTML shell, the page may be assembling its content in the browser. This checklist shows how to scrape a JavaScript-rendered website with Playwright, choose reliable waits, handle lazy loading and infinite scroll, capture downloads and screenshots, and leave a maintainable extraction job behind.

Overview

A conventional scraper usually sends an HTTP request, receives HTML, and parses it with a library such as Beautiful Soup. That approach remains preferable when the server response already contains the data or exposes a documented endpoint. A JavaScript-rendered website is different: the initial response may contain only a root element, script references, and application metadata. The browser then runs JavaScript, makes additional requests, and inserts the visible content into the DOM.

Playwright is useful in this situation because it controls a real browser engine and provides locators, navigation methods, download events, screenshots, and isolated browser contexts. It is a browser automation tool, not a substitute for understanding the target’s data flow. Before using it, check whether a stable, permitted API or server-rendered page can provide the same information with less overhead. The comparison below is a practical starting point:

SituationPreferred approachReason
Data is present in the initial HTMLDirect HTTP request and HTML parserSimpler, faster, and easier to test
Data arrives from a documented endpointUse the endpoint within its allowed termsReturns structured data without rendering a page
Content appears only after browser executionPlaywright browser automationCan observe the rendered DOM and user-visible interactions
Content requires scrolling, clicking, or a downloadPlaywright, possibly combined with direct requestsBrowser actions can trigger the required state

For background on finding data endpoints, see HTML scraping versus API access. If you do use browser automation, keep the collection narrow, cache results, respect applicable access rules, and avoid collecting data you do not need.

Minimal Playwright setup

For Python, install the package and then install the browser binaries required by your environment:

python -m pip install playwright
python -m playwright install chromium

A minimal synchronous script looks like this:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://example.com/catalog", wait_until="domcontentloaded")
    page.locator("article.product").first.wait_for()
    titles = page.locator("article.product h2").all_inner_texts()
    print(titles)
    context.close()
    browser.close()

The important pattern is the browser-context boundary. A context gives a job its own cookies, storage, permissions, and pages. Create a fresh context for separate accounts or jobs rather than allowing state to leak between them. In an asynchronous application, use Playwright’s async API and await each browser operation instead of mixing synchronous and asynchronous styles.

Checklist by scenario

Scenario 1: The response contains an empty application shell

  1. Open the page in a browser and identify the element that should contain the result.
  2. Choose a locator based on stable semantics, such as a role, label, or distinctive data attribute. Avoid relying on long generated class names.
  3. Navigate with an appropriate initial condition. domcontentloaded confirms that the document has been parsed; it does not guarantee that application data is ready.
  4. Wait for the result locator, a known loading indicator to disappear, or a specific application state.
  5. Extract text, attributes, links, or structured data only after the relevant content exists.

Prefer locator-based waits over arbitrary sleeps. For example:

page.goto(url, wait_until="domcontentloaded")
results = page.locator("[data-testid='search-result']")
results.first.wait_for(state="visible", timeout=15000)
rows = results.evaluate_all("els => els.map(e => ({text: e.innerText, href: e.querySelector('a')?.href}))")

If the site displays a loading skeleton, waiting for the first result may be more reliable than waiting for a fixed amount of time. If a page has several valid empty states, explicitly handle each one so an empty result is not mistaken for a failed scrape.

Scenario 2: Lazy-loaded content appears while scrolling

Lazy loading may be triggered by viewport visibility, scroll position, or an intersection observer. Scroll in measured steps and stop when the page stops producing new records. Use a count or stable identifier rather than assuming a particular number of scrolls.

items = page.locator("article.product")
previous_count = 0
stable_rounds = 0

for _ in range(40):
    current_count = items.count()
    if current_count == previous_count:
        stable_rounds += 1
    else:
        stable_rounds = 0
        previous_count = current_count

    if stable_rounds >= 3:
        break

    page.mouse.wheel(0, 1200)
    page.wait_for_timeout(500)

The short delay above is not the primary synchronization mechanism; it gives a browser event cycle time to run after the scroll. For stronger synchronization, wait for the item count to increase, a network response associated with the next page, or a “no more results” marker. Set a maximum number of iterations and record why the loop stopped.

Scenario 3: The page uses a “Load more” control

Locate the control by its accessible name and click it while it remains enabled. Capture the number of records before the click, then wait for that number to change or for a loading indicator to finish.

load_more = page.get_by_role("button", name="Load more")
items = page.locator("article.product")

for _ in range(20):
    before = items.count()
    if not load_more.is_visible() or not load_more.is_enabled():
        break
    load_more.click()
    page.wait_for_function(
        "([selector, before]) => document.querySelectorAll(selector).length > before",
        ["article.product", before]
    )

Some interfaces replace the button or disable it temporarily. Re-query the locator in each iteration rather than keeping assumptions about the old DOM node.

Scenario 4: A user action triggers a file download

Register the download expectation before clicking. This prevents a fast download event from being missed.

with page.expect_download(timeout=15000) as download_info:
    page.get_by_role("button", name="Export").click()

download = download_info.value
download.save_as("output/catalog.csv")

Use a deliberate filename and create the destination directory before the job runs. Check the suggested filename, MIME type where available, and file size. A successful browser event does not by itself prove that the file contains the expected data.

Scenario 5: Evidence and debugging are needed

Capture a screenshot after the page reaches the intended state:

page.screenshot(path="artifacts/catalog.png", full_page=True)

For difficult failures, save the rendered HTML, console messages, and a small trace or request log according to the sensitivity of the job. Screenshots are especially useful when a selector works locally but fails in a scheduled environment. Do not store credentials, tokens, or personal data in artifacts unless there is a clear operational need and suitable protection.

What to double-check

Wait strategy

Use the narrowest reliable condition. A page-level “network idle” condition can be unsuitable for applications that keep analytics, polling, or live connections open. A specific locator, response, or state change usually expresses the real requirement more clearly. Give each operation a bounded timeout and include the URL, step, and selector in error logs.

Selectors and extraction

Prefer semantic locators and stable attributes. Validate that each extracted record has the fields your downstream process expects. Normalize whitespace, preserve source URLs, and distinguish a missing field from an intentionally empty value. The selectors guide covers patterns for making extraction less fragile.

Pagination and duplicates

Infinite scroll can append the same record more than once, especially after retries or state restoration. Deduplicate using a stable source identifier when available, not only the visible title. Store progress and make the job restartable. The guide to incremental scraping provides a useful model for resuming jobs without reprocessing everything.

Browser lifecycle

Close pages, contexts, and browsers in a predictable cleanup path, including error paths. A context that remains open can retain memory, cookies, and temporary files. For repeated jobs, measure memory use and split work into bounded batches rather than keeping one page alive indefinitely.

Site behavior and collection boundaries

Confirm that your intended use is allowed, avoid bypassing access controls, and apply conservative concurrency and request pacing. Browser automation can generate substantially more activity than a single HTTP request because it loads scripts, styles, images, and background resources. For operational guidance, see how to build a polite web crawler.

Common mistakes

  • Parsing the initial HTML only: The data may not exist until JavaScript executes. Inspect the rendered DOM or identify the underlying endpoint.
  • Using fixed sleeps everywhere: A sleep can be too short on a slow run and wasteful on a fast one. Wait for a meaningful state change instead.
  • Waiting for the whole page to be quiet: Persistent connections can prevent the condition from completing. Wait for the result component or a specific response.
  • Using brittle CSS classes: Framework-generated classes often change. Choose roles, labels, data attributes, or structural relationships that reflect the interface.
  • Ignoring empty and terminal states: “No results,” “end of list,” and an error banner require different handling. Record which state occurred.
  • Clicking before registering a download listener: The event can be missed. Set up expect_download first.
  • Skipping validation: A page can render successfully while returning partial or changed data. Check row counts, required fields, URLs, and representative values.
  • Leaving debugging artifacts uncontrolled: Screenshots, traces, and HTML may contain sensitive content. Store them deliberately and clean them up.

When failures involve empty results, blocked requests, or changing response codes, use the scraping errors troubleshooting guide alongside your browser logs. Once extraction works, add fixtures and schema checks as described in testing and monitoring web scrapers.

When to revisit

Revisit this workflow whenever the target changes its frontend framework, rendering sequence, selectors, authentication flow, pagination behavior, or download format. Also review it before a seasonal planning cycle or any increase in collection volume. Browser binaries, Playwright APIs, and deployment environments can change, so verify installation commands and supported options in the version used by your project rather than copying an old setup indefinitely.

Use this final checklist before putting a dynamic website scraper into a scheduled workflow:

  1. Test whether direct HTML or an allowed structured endpoint is sufficient.
  2. Document the target URL, required state, selectors, and expected output fields.
  3. Create an isolated browser context and keep credentials out of source code.
  4. Replace arbitrary waits with locator, response, or state-based waits where possible.
  5. Bound infinite-scroll and pagination loops with a clear termination rule.
  6. Handle empty states, retries, downloads, screenshots, and cleanup explicitly.
  7. Deduplicate records and validate a sample against the visible page.
  8. Log enough context to diagnose a failure without exposing sensitive data.
  9. Monitor row counts and schema changes after deployment.

For pages that are mostly static, a conventional Python scraper may remain the better tool; see Requests, Beautiful Soup, and pagination. Use Playwright when browser execution is genuinely part of the page’s behavior, and keep the workflow small, observable, and easy to update when that behavior changes.

Related Topics

#playwright#javascript-rendering#browser-automation#infinite-scroll#web-scraping
s

scraper.page Editorial Team

Developer Workflow Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.