Use playwright web scraping to collect rendered records by opening a page, waiting for a dataset-specific completion signal, extracting fields, and exporting validated results. Prefer an official API when it exposes the required data.
This Python guide starts with a practice-site scraper, then covers CSV and JSON exports, dynamic lists, pagination, proxies, and troubleshooting. The core checks are simple: define readiness, preserve stable identifiers, validate fields, and record why collection stopped.
These examples have not been execution-tested. Install Playwright and Chromium first; each snippet states its required variables and where to insert it. Review the target site’s terms and robots.txt before collection, and consult our web scraping legal guide for project-specific considerations.
Key Facts
When should you use Playwright web scraping?
Use playwright web scraping when the required records depend on browser rendering or interaction. Start with an official API, export, or ordinary HTML request if that already meets the collection requirement.
A browser loads the document, executes page scripts, and updates the document object model, or DOM. Your scraper then selects elements from that current page state; it must separately establish whether all required records have arrived. The official Python library guide introduces browser launch, navigation, and page interaction.

| Approach | Use it when… | Avoid it when… |
|---|---|---|
| Official API or export | Use an official API when its documented fields and access rules meet your requirements. | Avoid an API-based implementation when essential fields are unavailable through that interface. |
| HTML request | Use an HTML request when the response already contains the records. | Avoid HTML-only extraction when the necessary data appears only after browser interaction. |
| Browser automation | Use browser automation when rendering, navigation, or permitted interaction is necessary. | Avoid browser automation when it adds complexity without changing the accessible data. |
Before choosing playwright for web scraping, define the required fields, stable identifiers, expected coverage, and request budget. Our headless browser guide adds background on browser-based workflows.
Playwright web scraping in Python: install and run
Install the Python package and its browser binary, then navigate to a practice page and extract a small set of fields. The package installation and browser installation are separate steps.
Example installation commands, following the Python installation documentation:
python -m pip install playwright
python -m playwright install chromium
On Linux, the browser dependency instructions also document python -m playwright install --with-deps chromium. Installing operating-system packages may require administrator privileges.
Books to Scrape identifies itself as a scraping practice site. Its catalog makes a small extraction example, although browser rendering is unnecessary for this particular HTML page. The example collects only the current page and does not claim complete catalog coverage.
Run this as a standalone Python script after installation; it requires no pre-existing variables. Markup may change:
from urllib.parse import urljoin
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
response = page.goto("https://books.toscrape.com/", wait_until="load")
if response is None or not response.ok:
raise RuntimeError("Catalog request failed")
cards = page.locator("article.product_pod")
cards.first.wait_for(state="visible")
records = []
for card in cards.all():
link = card.locator("h3 a")
href = link.get_attribute("href")
title = link.get_attribute("title")
if not href or not title:
raise ValueError("Missing book link or title")
records.append({
"id": urljoin(page.url, href),
"title": title,
"price": card.locator(".price_color").inner_text().strip(),
})
browser.close()
print(records)
The product URL acts as the example’s identifier. The first-card wait checks that the expected layout exists; it is not a general completeness check for dynamic lists. On another site, replace both the selectors and the readiness condition.
Extract records and export CSV or JSON
Validate required fields and deduplicate by a stable identifier before serializing records. Keep the raw row count and unique count separate so repeated records remain visible in your collection report.
Continue with the records variable from the previous example. This block writes books.json and books.csv to the current working directory.
import csv
import io
import json
unique = {}
for row in records:
if any(not row.get(key) for key in ("id", "title", "price")):
raise ValueError("Incomplete record")
previous = unique.get(row["id"])
if previous is not None and previous != row:
raise ValueError("Conflicting records share an identifier")
unique[row["id"]] = row
rows = list(unique.values())
json_text = json.dumps(rows, ensure_ascii=False, indent=2)
buffer = io.StringIO(newline="")
writer = csv.DictWriter(buffer, fieldnames=["id", "title", "price"])
writer.writeheader()
writer.writerows(rows)
with open("books.json", "w", encoding="utf-8") as output:
output.write(json_text)
with open("books.csv", "w", encoding="utf-8", newline="") as output:
output.write(buffer.getvalue())
Do not silently overwrite conflicting rows unless you have a defined update policy. A repeated identifier with a changed price may represent a legitimate update, a selector mistake, or inconsistent page state.
Keep prices as source text until you have a deliberate currency and number-parsing policy. For production exports, also record the collection timestamp, source URL, raw rows, unique rows, rejected rows, and stop reason. A valid JSON document can still contain an incomplete dataset.
Wait for dynamic content and inspect JSON responses
Wait for evidence that the required dataset is complete, rather than assuming navigation or the first visible row means collection is ready. Inspect a relevant JSON response when it offers clearer identifiers and pagination metadata.
Playwright’s
locator.all()returns currently matching elements without waiting. Wait for a dataset-specific completion signal before extracting dynamic lists.
The official locator.all() documentation explicitly warns about changing lists. Playwright’s actionability checks help an interaction wait for a usable element; they do not establish that your entire dataset has loaded.
Use this 5-step extraction readiness check:
- Step 1: Scope. Establish the permitted URLs, fields, collection frequency, and intended reuse.
- Step 2: Response status. Check the document response and the response carrying the records.
- Step 3: Readiness signal. Wait for an application completion marker, expected identifier set, or confirmed terminal page.
- Step 4: Field validation. Reject missing identifiers and malformed required fields.
- Step 5: Completeness. Compare unique records with the expected set or report that only observed coverage is known.
A fixed sleep is a timing guess. A quiet network can also be unrelated to record completeness. Prefer a signal whose meaning you can explain, such as a completed final batch and its expected identifiers.
When should you read JSON responses instead of the DOM?
Use a response body when an allowed page workflow returns the fields you need in a structured format. If the operator publishes an official API for those records, prefer that documented API; a browser’s internal request is not automatically a public API.
Insert this block inside the existing with sync_playwright() as p: block, after creating page and before calling browser.close(). Indent it to match that block. Set TARGET_URL and DATA_URL first in the process environment, using the approved page and its exact data-request URL. The records key is an example application schema, not a Playwright field.
import os
with page.expect_response(
lambda r: r.url == os.environ["DATA_URL"]
and r.request.method == "GET"
) as pending:
page.goto(os.environ["TARGET_URL"])
response = pending.value
if not response.ok:
raise RuntimeError(f"Data request failed: {response.status}")
if "application/json" not in response.headers.get("content-type", ""):
raise ValueError("Expected a JSON response")
payload = response.json()
if not isinstance(payload, dict) or not isinstance(payload.get("records"), list):
raise ValueError("Unexpected response schema")
records = payload["records"]
Register the wait before the action that triggers the request. The documented expect_response() context manager captures the response, and response.json() parses its body. Validate each record and any continuation token before accepting the result.
Pagination, Load More, and infinite scroll
Collect each confirmed batch into one identifier map, then advance only after recording the current state. Stop on a reliable end condition or a declared safety limit, and distinguish those outcomes.
- Numbered pages: extract the current page, follow Next, and confirm that the page token or identifier set changed.
- Load More: capture the existing identifiers, activate the control, and wait for a batch completion signal before extracting again.
- Infinite scroll: trigger the next load and confirm new identifiers or an explicit end marker. A single unchanged viewport is not proof of completion.
- Virtualized lists: preserve records as you observe them. A final DOM snapshot may represent only the currently rendered window.
This helper extends the practice-site example and uses its urljoin import. Define it before the browser block. Call records, stop_reason, raw_rows = collect_pages(page) after navigation and before closing the browser. Calculate duplicate occurrences as raw_rows - len(records). Its page limit is an example policy, not a service limit.
def collect_pages(page, max_pages=3):
unique, visited = {}, set()
raw_rows = 0
for _ in range(max_pages):
if page.url in visited:
raise RuntimeError("Pagination repeated a page")
visited.add(page.url)
cards = page.locator("article.product_pod")
cards.first.wait_for(state="visible")
for card in cards.all():
raw_rows += 1
link = card.locator("h3 a")
href = link.get_attribute("href")
if not href:
raise ValueError("Missing product URL")
key = urljoin(page.url, href)
row = {
"id": key,
"title": link.get_attribute("title"),
"price": card.locator(".price_color").inner_text().strip(),
}
if any(not row.get(field) for field in ("id", "title", "price")):
raise ValueError("Incomplete record")
previous = unique.get(key)
if previous is not None and previous != row:
raise ValueError("Conflicting records share an identifier")
unique[key] = row
next_link = page.locator("li.next a")
if next_link.count() == 0:
return list(unique.values()), "end_of_catalog", raw_rows
if len(visited) == max_pages:
break
href = next_link.get_attribute("href")
if not href:
raise ValueError("Missing next-page URL")
response = page.goto(urljoin(page.url, href), wait_until="load")
if response is None or not response.ok:
raise RuntimeError("Pagination request failed")
return list(unique.values()), "page_limit", raw_rows
The helper’s readiness assumption fits this HTML catalog, not arbitrary dynamic feeds. Apply the field validation from the export section afterward. If a run stops at page_limit, describe the output as partial even when every collected row is valid.
Configure Playwright proxies in Python
Configure a proxy at browser launch or when creating a browser context, and keep credentials in environment variables. Check the route from the same context that will perform collection.
The official proxy documentation describes HTTP(S) and SOCKSv5 routing. Its optional username and password settings apply to HTTP(S) proxy authentication; do not assume those fields enable authenticated SOCKS connections.
Run this as a standalone script for an authenticated HTTP(S) proxy. Set PROXY_SERVER, PROXY_USERNAME, and PROXY_PASSWORD in the process environment. Set EXIT_IP_URL to an approved endpoint that returns the caller’s IP as plain text.
import os
from playwright.sync_api import sync_playwright
proxy = {
"server": os.environ["PROXY_SERVER"],
"username": os.environ["PROXY_USERNAME"],
"password": os.environ["PROXY_PASSWORD"],
}
with sync_playwright() as p:
browser = p.chromium.launch(proxy=proxy)
context = browser.new_context()
page = context.new_page()
response = page.goto(os.environ["EXIT_IP_URL"])
if response is None or not response.ok:
raise RuntimeError("Exit-IP check failed")
print(page.locator("body").inner_text().strip())
context.close()
browser.close()
For context-level routing, replace the browser and context creation lines inside the preceding with sync_playwright() as p: block with the following alternative, keeping their indentation and the existing proxy variable, as documented under browser.new_context(proxy=…):
browser = p.chromium.launch()
context = browser.new_context(proxy=proxy)
Compare the reported IP with the route you expect, then navigate to the target using that same context. An IP echo confirms the route to that endpoint at that moment; it does not prove that every destination will accept the connection.
A proxy changes network routing, but browser automation can still be detected. Keep routing consistent when collection depends on session continuity.
Product note: DataImpulse is our product. Its residential proxies start at $1 per GB with pay-as-you-go billing, free country targeting, and rotating or sticky sessions.
Use sticky sessions when a multi-step collection needs a consistent route; do not treat them as permanent IP assignments or promises of access. Our proxy selection guide covers additional selection considerations.
Troubleshoot timeouts, rate limits, and detection
Classify the failure before retrying or changing the route. Preserve enough evidence to distinguish a slow dataset, a broken selector, a rejected request, and an incomplete export.
| Symptom | Inspect first | Next action |
|---|---|---|
| Timeout | Completion marker, data response, screenshot, and current URL | Identify the operation that timed out. Check the response, selector, and readiness signal; increase the timeout only when observed loading times justify it. |
| Missing records | Pagination state, unique identifiers, and expected total | Check whether extraction happened before the final batch. |
| Missing fields | One failing record and its matching DOM elements | Repair selectors or schema handling; preserve rejected rows. |
| HTTP 401 or 403 | Authentication state and access requirements | Review access before attempting another collection. |
| HTTP 429 | Response headers and collection concurrency | Honor Retry-After when present and reduce request pressure. |
| Challenge page | Page content and the expected application state | Record the challenge as a failed collection, not a successful empty export. |
The HTTP 429 documentation explains the rate-limit response and optional Retry-After header. Use bounded retries for appropriate temporary failures, with a maximum attempt count and an explicit final failure state.
Changing an IP cannot repair incomplete extraction or establish permission. Network routing, browser-visible properties, session state, and interaction patterns are separate concerns. Do not assume a successful exit-IP check means the browser will avoid detection.
Patchright modifies Playwright, while Camoufox is a Firefox-based browser. Check their official documentation for supported versions and integration requirements before replacing the browser setup used in this guide.
For challenge-related workflows, our CAPTCHA handling article offers additional context. Record unresolved challenges separately from transport errors and valid zero-result pages.
Playwright vs Selenium vs Puppeteer
Choose the framework around your team’s language, browser requirements, and existing automation infrastructure. The comparison below describes documented capabilities and maintenance considerations, not measured performance rankings.
| Framework | Languages and browsers | Synchronization and infrastructure | Maintenance consideration |
|---|---|---|---|
| Playwright | Python, JavaScript/TypeScript, Java, and .NET; Chromium, Firefox, and WebKit. | Locator actionability checks and explicit waits for application-specific conditions. | Keep the package and its browser installations aligned; maintain dataset readiness separately from interaction waits. |
| Selenium | Bindings include Python, Java, JavaScript, C#, and Ruby; browser documentation covers Chrome, Edge, Firefox, and Safari. | Explicit and implicit waits; Grid for remote browser execution; WebDriver BiDi for bidirectional capabilities. | Validate the required browser and binding combination. Existing Grid infrastructure can be a reason to retain Selenium. |
| Puppeteer | JavaScript library with TypeScript APIs; Chrome and Firefox. | Locator-based interaction waits and browser control through supported protocols. | Check the supported browser versions and protocol capabilities needed by the workflow. |
Competitor data: taken from each provider’s official pricing and documentation pages linked in this article, collected on November 10, 2026.
Framework capabilities were checked against the official documentation linked below on November 10, 2026. This table does not compare pricing or measured performance.
Official sources: Playwright languages, browsers, and auto-waiting; Selenium WebDriver documentation, waiting strategies, Grid, and WebDriver BiDi; Puppeteer library overview, supported browsers, and page interactions.
Puppeteer is not Chrome-only. Selenium also documents automated driver management through Selenium Manager, so manual driver downloads are not an inherent requirement.
Check extraction completeness with a local fixture
Use a controlled localhost fixture to check extraction timing against a known identifier set.
Run this self-contained example as a standalone Python script after installing Playwright and Chromium; it requires no pre-existing variables. It serves three delayed batches with deliberately repeated identifiers. Its design contains six rendered rows and four unique identifiers. Those are fixture expectations, not observed outcomes.
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from playwright.sync_api import sync_playwright
HTML = b"""<main id="rows" data-complete="false"></main>
<script>
const root = document.querySelector('#rows');
[[1, 2], [2, 3], [3, 4]].forEach((batch, i) => {
setTimeout(() => {
for (const id of batch) {
const row = document.createElement('p');
row.dataset.id = String(id);
row.textContent = 'Record ' + id;
root.appendChild(row);
}
if (i === 2) root.dataset.complete = 'true';
}, 300 * (i + 1));
});
</script>"""
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(HTML)
server = HTTPServer(("127.0.0.1", 0), Handler)
Thread(target=server.serve_forever, daemon=True).start()
try:
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto(f"http://127.0.0.1:{server.server_port}")
page.locator('#rows[data-complete="true"]').wait_for()
ids = page.locator("[data-id]").evaluate_all(
"nodes => nodes.map(node => node.dataset.id)"
)
assert set(ids) == {"1", "2", "3", "4"}
print({"rows": len(ids), "unique": len(set(ids))})
browser.close()
finally:
server.shutdown()
server.server_close()
The completion attribute is an explicit contract between the fixture and extractor. The documented evaluate_all() method reads the matching elements after that contract is satisfied.
How should you measure extraction completeness?
For a local experiment, compare immediate extraction with completion-based extraction using ten repetitions of each variant. Use a fresh browser context for each repetition and record the elapsed interval from navigation start to extraction finish. Keep browser startup outside that interval or report it separately.
For every repetition, retain the expected identifier set, observed identifiers, raw row count, unique count, missing identifiers, duplicates, exception status, and elapsed duration. Calculate duplicates as raw rows minus unique identifiers. Calculate missing records using set difference, not merely the difference between two counts.
Publish the actual execution date, Python version, Playwright version, browser version, operating system, timeout policy, and raw per-run results alongside any summary. Report failures separately rather than hiding them inside a median of successful runs. Describe the result as a local snapshot, not a benchmark.
Does blocking images improve resource use?
This fixture contains no images and cannot test image blocking. For an image-bearing page, compare transferred response-body bytes and elapsed time with image requests enabled and blocked, and verify that both runs collect the same identifiers. The network routing documentation explains request interception.
Frequently Asked Questions
Is Playwright good for web scraping?
It is useful when a collection requires browser rendering or interaction. Start with the simplest interface that exposes the required records, and use browser automation when that workflow needs it.
How do you scrape a website with Playwright in Python?
Install the package and browser, navigate to the target, and establish a readiness condition tied to the records. Extract fields, validate identifiers, and serialize the accepted rows. Record whether the run reached its intended end condition.
How should Playwright wait for dynamic content?
Choose a signal that means the intended batch or dataset has finished loading. A visible row only proves that at least one row is present. Confirm the resulting identifier set before claiming complete coverage.
How do you scrape infinite scroll without missing or duplicating records?
Merge each completed batch into a map keyed by stable identifiers before triggering another load. Preserve records that may disappear from the rendered window. If the source exposes no reliable end signal, label the result as observed coverage.
Should you extract JSON responses or page elements?
Prefer a documented official API when it contains the necessary fields. Otherwise, choose the representation that makes identifiers, fields, and pagination easiest to validate within the allowed workflow. An internal JSON endpoint still needs its own access and schema checks.
Will a residential proxy prevent Playwright detection?
No proxy can guarantee that a browser workflow will be accepted. Keep routing consistent when session continuity matters, and distinguish routing problems from challenges, authentication failures, and extraction errors.
Does blocking images make a scraper faster?
Treat that as a measurement question for the actual workload. Compare elapsed time and response bytes while checking the same expected records in both variants. Lower traffic alone is insufficient evidence of faster completion.
Should a scraper retry every failure?
No. A schema error or access rejection needs investigation rather than repeated requests. For appropriate temporary failures, use bounded retries, honor requested delays, and retain the final failure reason.
Last updated: November 10, 2026.
