Web scraping
Web scraping with Playwright: contexts, locators and network capture
Playwright drives a real browser engine, so pages built by JavaScript render for your script the same way they render for a visitor. This guide covers the three features that matter most for collecting data: contexts, locators and response capture.
Why Playwright suits modern pages
Pick Playwright when the data you want only exists after scripts run. A plain HTTP client receives the first HTML document and nothing else; if the product list, the prices or the search results are filled in later by a framework, that document is an empty shell. A headless browser executes those scripts, waits for the network to settle and gives you the finished DOM.
Playwright adds three things that make it pleasant for this job. Contexts give you cheap, isolated sessions inside one browser process. Locators wait for elements on their own, so you rarely write sleeps. And the network layer lets you read the JSON a page downloads, which is often cleaner than the HTML it renders. The examples below use the synchronous Python API; the async API and the Node.js library expose the same ideas under nearly identical names.
Install the library and a browser
Install the package and then download a browser build. The second command matters: the Python package alone does not include Chromium.
python -m pip install playwright
python -m playwright install chromium
On a fresh Linux server you may also need system libraries; python -m playwright install --with-deps chromium pulls them in on common distributions. Pin the Playwright version in your requirements file, because each release is tied to specific browser builds and an unpinned upgrade can change rendering behavior overnight.
Separate sessions with browser contexts
A browser context is an isolated profile: its own cookies, local storage, cache and permissions. Launching a browser is slow, while opening a context takes milliseconds, so the usual pattern is one browser per worker and one context per logical session. Two contexts never see each other's cookies, which is exactly what you want when you crawl two regions or two accounts side by side.
from playwright import sync_api
with sync_api.sync_playwright() as pw_driver:
engine = pw_driver.chromium.launch(headless=True)
us_view = engine.new_context(locale="en-US", timezone_id="America/Chicago",
viewport={"width": 1366, "height": 860})
uk_view = engine.new_context(locale="en-GB", timezone_id="Europe/London")
for ctx in (us_view, uk_view):
tab = ctx.new_page()
tab.goto("https://example.com/deals", wait_until="domcontentloaded")
print(ctx is us_view, tab.title())
engine.close()
Set the locale, time zone and viewport on the context rather than leaving defaults. Those values show up in JavaScript and in request headers, and a context that claims one region while its time zone says another looks odd to bot detection. Contexts can also carry a proxy of their own through the proxy argument of new_context, so each session can leave from a different address.
Keeping a session between runs
When a site sets cookies after a consent banner or a sign-in you are allowed to perform, save the context state and load it next time. ctx.storage_state(path="session.json") writes cookies and local storage to disk, and engine.new_context(storage_state="session.json") restores them. Treat that file like a password.
Find elements with locators
Locators describe how to find an element, not a snapshot of it. Every action on a locator re-queries the page and waits until the element is attached and visible, which removes most timing bugs. Prefer locators that read like the page itself: roles, labels and visible text survive redesigns better than long chains of class names.
cards = tab.locator("li.result-card")
cards.first.wait_for(timeout=15_000)
rows = []
for card in cards.all():
rows.append({
"title": card.get_by_role("heading").inner_text().strip(),
"price": card.locator("[data-test=price]").inner_text(),
"href": card.get_by_role("link").first.get_attribute("href"),
})
more = tab.get_by_role("button", name="Load more")
if more.is_visible():
more.click()
A few habits keep locator code healthy. Call .all() only after waiting for the first match, because it returns whatever exists at that instant. Use .first or a narrower selector when a locator could match several nodes, since actions on an ambiguous locator raise a strict mode error. And when you need many fields from many rows, a single tab.eval_on_selector_all() call that returns a list of dictionaries is far faster than hundreds of separate round trips. The CSS selector and text engines can be mixed freely in one locator chain.
Read the data from network responses
Often the fastest route to clean data skips the HTML entirely. Single page apps fetch JSON from an internal endpoint and then render it; if you capture that response, you get typed fields, full precision and items that the layout may truncate. Open the network tab in your own browser first, filter by Fetch/XHR, and note the URL pattern of the call that carries the data.
def is_listing(resp):
return "/api/v2/listings" in resp.url and resp.ok
with tab.expect_response(is_listing, timeout=20_000) as caught:
tab.get_by_role("button", name="Next page").click()
payload = caught.value.json()
for item in payload.get("items", []):
print(item.get("sku"), item.get("price"))
expect_response arms the listener before the click, so you never miss a response that arrives quickly. For a passive log of everything, register tab.on("response", handler) instead and filter inside the handler. Reading the body inside a response event is fine for small payloads; for large ones, collect the URLs and fetch them later with the context's request object, which reuses the same cookies. This approach is a close cousin of hidden API scraping, with the browser doing the authentication work for you.
Skip downloads you do not need
Images, fonts and video rarely carry data, yet they dominate page weight. Route them away at the context level so every tab benefits:
HEAVY = {"image", "media", "font"}
us_view.route("**/*", lambda route: route.abort()
if route.request.resource_type in HEAVY else route.continue_())
Be careful with stylesheets on sites that check layout, and never block the scripts of a bot check, because the check will simply fail to finish.
When a CAPTCHA appears mid-crawl
Detect the widget, solve it through the API, then hand the answer to the page. A reCAPTCHA checkbox or a Turnstile box exposes its site key in a data-sitekey attribute, which a locator reads directly. The token returned by a task goes into the hidden response field, and the form is submitted as usual.
import time, requests
def fetch_token(url, key, kind="AntiTurnstileTaskProxyLess"):
spec = {"type": kind, "websiteURL": url, "websiteKey": key}
job = dict(clientKey="YOUR_API_KEY", task=spec)
tid = requests.post("https://gatesolver.com/createTask", json=job).json()["taskId"]
for _ in range(40):
time.sleep(3)
r = requests.post("https://gatesolver.com/getTaskResult",
json={"clientKey": "YOUR_API_KEY", "taskId": tid}).json()
if r.get("status") == "ready":
return r["solution"]["token"]
if r.get("errorId") or r.get("status") == "failed":
return None
return None
widget = tab.locator(".cf-turnstile[data-sitekey]")
if widget.count():
token = fetch_token(tab.url, widget.get_attribute("data-sitekey"))
tab.locator("input[name=cf-turnstile-response]").evaluate(
"(el, v) => { el.value = v; }", token)
For a reCAPTCHA v2 checkbox, switch the type to ReCaptchaV2TaskProxyLess, read gRecaptchaResponse from the solution and write it into textarea#g-recaptcha-response. If the page reacts through a JavaScript callback instead of a form post, call that callback with the token. The per-type fields are listed on each type page, such as Cloudflare Turnstile and reCAPTCHA v2, and the Playwright integration guide wraps the same idea in a reusable helper.
Run it without surprises
Production crawls fail in boring ways, so plan for them. Set a default timeout on the context with ctx.set_default_timeout(20_000) so a stuck page cannot hang a worker. Close pages you are done with; a context with hundreds of open tabs eats memory quickly. Record a trace with ctx.tracing.start(screenshots=True, snapshots=True) while you develop, then open it with python -m playwright show-trace to replay exactly what the browser saw.
Pace your requests per site, keep the crawl to public pages you are allowed to collect, and cache responses so a rerun does not hit the server again. Playwright makes it easy to open many tabs, but a gentle crawl is both kinder to the site and less likely to meet a challenge in the first place.
Common questions
Is the sync or async Playwright API better for scraping?
The sync API is simpler for scripts and small jobs. The async API lets one process drive many pages at once, which pays off when you crawl thousands of URLs.
How many contexts can one browser hold?
There is no fixed number; memory is the limit. A few dozen light contexts per browser is common, and you should close each one when its session ends.
Can Playwright read a JSON response without rendering the page?
Yes. The request object on a context sends plain HTTP calls with the same cookies, so once you know the endpoint you can call it directly.
Does blocking images change how a site treats my browser?
It can on a few sites that measure loading behavior. Start by blocking only media and fonts, and turn it off if challenges become more frequent.
Which token field do I fill for a Turnstile widget?
Write the token into the hidden input named cf-turnstile-response inside the form, or pass it to the callback the site registered for the widget.
Keep reading
- PlaywrightPlaywright in Node.js and Python: read widget keys from the DOM or network, inject tokens, and add answers through route interception.
- PlaywrightA browser automation library for Chromium, Firefox and WebKit with isolated contexts, auto waiting and network control built in.
- Scrapy with PlaywrightRender only the requests that need JavaScript: scrapy-playwright settings, page methods, page objects, contexts and blocking heavy resources.
- Cloudflare Turnstile solver$0.84 per 1,000 tasks, answers under 3 seconds.