Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c24507b5a | ||
|
|
39010ed45e | ||
|
|
d34a11e886 | ||
|
|
5f528357a6 | ||
|
|
70a8164d26 | ||
|
|
8a8dc8d0fd | ||
|
|
648aacfabd | ||
|
|
c61579c2f4 | ||
|
|
0bd093d285 | ||
|
|
61fde53457 | ||
|
|
823217b484 | ||
|
|
b8243bb0c2 | ||
|
|
0f14cc782d | ||
|
|
d4faa9ebaf | ||
|
|
39e4dd2e0f | ||
|
|
76a7a0ce21 | ||
|
|
0d65c54eb6 | ||
|
|
5a786f43d6 | ||
|
|
1f6f8d1ac8 | ||
|
|
95c791d351 | ||
|
|
907150bf60 | ||
|
|
d86f52c9c8 | ||
|
|
686607738e | ||
|
|
e2b795eea4 | ||
|
|
4ddf1f9fb7 |
No files matched your search
@@ -179,8 +179,40 @@ jobs:
|
||||
# turn that choice into a red and push toward dropping the protection on
|
||||
# release day of all days. So it refuses on `failure` and `cancelled`,
|
||||
# never on `skipped`.
|
||||
# The guides are the surface a stranger copies first, and until 2026-09-08
|
||||
# nothing read them: one page published `page.accessibility.snapshot()`, which
|
||||
# this fork does not have, so anybody who ran that block got an AttributeError.
|
||||
# A broken test is seen by whoever runs the suite; a broken guide is seen once,
|
||||
# by a reader who then leaves.
|
||||
#
|
||||
# It needs the package importable, because it asks the REAL classes what they
|
||||
# have rather than carrying a list that would drift from them - so it takes
|
||||
# core-on-index's answer exactly as `unit` does, and is SKIPPED during the
|
||||
# window rather than faked green.
|
||||
docs-api:
|
||||
name: the guides name an API that exists
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: pip
|
||||
- name: Install package
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e .
|
||||
- name: check the guides against the API
|
||||
# --selftest first, for the same reason the English gate does it: this
|
||||
# one goes blind from a single edit to the list of names it inspects.
|
||||
run: |
|
||||
python scripts/check_docs_api_surface.py --selftest
|
||||
python scripts/check_docs_api_surface.py
|
||||
|
||||
gate:
|
||||
needs: [core-on-index, unit]
|
||||
needs: [core-on-index, unit, docs-api]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -188,12 +220,16 @@ jobs:
|
||||
run: |
|
||||
echo "core-on-index: ${{ needs.core-on-index.result }}"
|
||||
echo "unit: ${{ needs.unit.result }}"
|
||||
echo "docs-api: ${{ needs.docs-api.result }}"
|
||||
case "${{ needs.unit.result }}" in
|
||||
failure|cancelled) echo "the suite did not pass"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.core-on-index.result }}" in
|
||||
failure|cancelled) echo "the index check did not run"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.docs-api.result }}" in
|
||||
failure|cancelled) echo "the guides name something that does not exist"; exit 1 ;;
|
||||
esac
|
||||
echo "ok"
|
||||
|
||||
# Measured 2026-09-04: 0.10.0 was on the index while main sat on 0.10.0 with
|
||||
|
||||
@@ -6,6 +6,61 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.13.2] - 2026-09-07
|
||||
|
||||
### Fixed
|
||||
- **`page.goto()` now answers with the Response, instead of always `None`.**
|
||||
The navigation itself was never broken - the page loaded, the `response`
|
||||
events carried the right statuses and `expect_response` worked - but the
|
||||
return value was hardcoded to `None`, so `page.goto(url).status` was not
|
||||
reachable. `page.reload()` answers with a Response too, and so does history
|
||||
navigation, which shares that code path but is still held back by a separate
|
||||
engine defect of its own. A redirect chain answers with the FINAL response,
|
||||
and a same-document navigation still answers `None`, as upstream does.
|
||||
Crawlee treats a `None` here as a failed load, so a `PlaywrightCrawler`
|
||||
driven by this package failed every request; it now finishes them.
|
||||
|
||||
## [0.13.1] - 2026-09-06
|
||||
|
||||
### Changed
|
||||
- **The engine is `firefox-29`, through `invisible-core 29.19.0`.** It carries
|
||||
the screencast that `page.screencast.start(on_frame=...)` needs, so the
|
||||
feature shipped in 0.13.0 now has an engine that answers it, and the
|
||||
full-window frame no longer carries the Windows resize border. Nothing
|
||||
else moves: the pin follows the seal.
|
||||
|
||||
## [0.13.0] - 2026-09-05
|
||||
|
||||
### Added
|
||||
- **`page.screencast.start(on_frame=...)` streams JPEG frames of the browser
|
||||
WINDOW.** `page.screenshot()` gives the content viewport and can never show
|
||||
the pointer, which is drawn in the chrome document precisely so that no page
|
||||
can see it. The screencast captures the window through the operating system
|
||||
in the parent process - tab strip, address bar and pointer included, nothing
|
||||
injected into the page - and hands each frame to `on_frame` as JPEG bytes
|
||||
with the captured window's size. Needs an engine from `firefox-28` on;
|
||||
`size=` bounds the frame (scaled down to fit, never up, default 1280x800)
|
||||
and `quality=` the JPEG quality (default 80). `path=` (a video file) is
|
||||
refused by name: the engine has no video encoder.
|
||||
|
||||
### Fixed
|
||||
- **Two threads writing the Juggler pipe could splice two commands into one
|
||||
line.** Frames are acknowledged from the reader thread while the caller's
|
||||
thread dispatches input; the pipe now has a write lock, and a
|
||||
`Connection.post` that sends without waiting for the reply.
|
||||
|
||||
## [0.12.3] - 2026-09-05
|
||||
|
||||
### Fixed
|
||||
- **Orphaned `.tmp-<tag>-<pid>` trees in the engine cache are swept.** Through
|
||||
`invisible-core 27.19.0`: a download killed during `verifying` or
|
||||
`extracting` used to leave up to the whole extracted tree behind, because
|
||||
only a fresh download by the same pid ever removed it. `ensure_binary` now
|
||||
removes the trees whose process is gone, on every call, and leaves alone
|
||||
this process's own tree, a live process's tree and anything not named after
|
||||
a pid. The MCP server 0.13.0 starts the download with the process, which made
|
||||
a killed download an ordinary event rather than a Ctrl-C.
|
||||
|
||||
## [0.12.2] - 2026-09-05
|
||||
|
||||
### Changed
|
||||
|
||||
+1669
File diff suppressed because it is too large.
Load diff
@@ -23,6 +23,14 @@ Anti-bots ask two questions, and reCAPTCHA, hCaptcha and Cloudflare Turnstile sc
|
||||
- Every click, hover and drag follows a natural mouse path with human timing, no teleporting cursor.
|
||||
- Each input is byte-identical to a real mouse: real input source, pressure, trusted events.
|
||||
|
||||
**And one thing the stock driver cannot do.** Playwright's own documentation says
|
||||
"Closed-mode shadow roots are not supported", and measured on 2026-09-05 against a page
|
||||
carrying one open and one closed root, stock Playwright returned zero matches for the
|
||||
closed content in Firefox and in Chromium alike. This engine returns the element, while
|
||||
the page still reads `null` from `element.shadowRoot`, so nothing observable to the page
|
||||
changes. The three-arm table and the page that reproduces it:
|
||||
[closed shadow roots](https://github.com/feder-cr/invisible_playwright/wiki/closed-shadow-root-playwright).
|
||||
|
||||
Driven by the standard Playwright API. Full breakdown: [feder-cr/firefox_antidetect_patch](https://github.com/feder-cr/firefox_antidetect_patch).
|
||||
|
||||
---
|
||||
@@ -49,8 +57,8 @@ This page is the engine, as a Python library. There are two ways to use it
|
||||
without writing code, and both are one line:
|
||||
|
||||
- **From an MCP client you already have** (Claude Code, Claude Desktop,
|
||||
Cursor): `claude mcp add stealth -- uvx invisible-playwright-mcp`. See
|
||||
[invisible-playwright-mcp](https://github.com/feder-cr/invisible-playwright-mcp).
|
||||
Cursor): `claude mcp add stealth -- uvx aihawk`. See
|
||||
[the MCP server page](https://github.com/feder-cr/AIHawk/wiki/mcp-server).
|
||||
- **With an interface and a model included**, needing only an OpenRouter key:
|
||||
`uvx aihawk ui --openrouter-key sk-or-...`. See
|
||||
[AIHawk](https://github.com/feder-cr/AIHawk).
|
||||
@@ -228,11 +236,11 @@ two around it are how most people reach it:
|
||||
|
||||
- **[invisible_core](https://github.com/feder-cr/invisible_core)** - seed to
|
||||
fingerprint to preferences, plus proxy and geolocation. This package pins it.
|
||||
- **[invisible-playwright-mcp](https://github.com/feder-cr/invisible-playwright-mcp)**
|
||||
- this engine as an MCP server, for any client that brings its own model.
|
||||
- **[AIHawk](https://github.com/feder-cr/AIHawk)** - an interface and a model,
|
||||
from one command. A client of the server above, with no private path to the
|
||||
browser.
|
||||
- **[AIHawk](https://github.com/feder-cr/AIHawk)** - this engine as an MCP
|
||||
server (`uvx aihawk`, for any client that brings its own
|
||||
model) and, in the same package, an interface with a model included, from
|
||||
one command. The interface is a client of the server, with no private path
|
||||
to the browser.
|
||||
|
||||
**The open-source neighbours**, and what each one is for.
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ see is a header an injection cannot fix.
|
||||
|
||||
## How this project keeps header and property in agreement
|
||||
|
||||
Because the fingerprint is applied at the browser level rather than in the page, the
|
||||
Because the fingerprint is applied at the browser level, not in the page, the
|
||||
language is set through the same native preference a real profile uses, so both surfaces
|
||||
read from it. There is nothing to inject into the page and nothing to keep in sync: the
|
||||
header and the array are the same value formatted twice, by the browser, the way they
|
||||
@@ -98,7 +98,7 @@ failure be replayed instead of guessed at.
|
||||
|
||||
## Prove they match, do not assume it
|
||||
|
||||
The point of this page is a check you can run rather than a claim to trust. Capture the
|
||||
The point of this page is a check you can run, not a claim to trust. Capture the
|
||||
`Accept-Language` header the browser actually sent, read `navigator.languages` from the
|
||||
loaded page, and compare the two directly. Use any endpoint that echoes request headers
|
||||
back; the snippet below reads the header off the outgoing request instead, so it needs no
|
||||
@@ -132,7 +132,7 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
|
||||
Follow the method from
|
||||
[how to test whether your browser is detected](how-to-test-bot-detection.md): assert the
|
||||
values are present and agree, rather than asserting nothing looks wrong. A property that
|
||||
values are present and agree, not asserting nothing looks wrong. A property that
|
||||
comes back empty, or a header your capture never saw, is a failure and not a pass. Run it
|
||||
against a stock browser on the same machine too, and the header and array should match
|
||||
there in exactly the same way.
|
||||
|
||||
@@ -69,7 +69,7 @@ and `headless` on `BrowserProfile`. The surrounding code is Chrome executable di
|
||||
and Chrome profile handling, and the channel type is a Chromium channel.
|
||||
|
||||
The useful move there is pointing `executable_path` at your **real installed Chrome**
|
||||
rather than the bundled Chromium, and pointing `user_data_dir` at a profile that has been
|
||||
instead of the bundled Chromium, and pointing `user_data_dir` at a profile that has been
|
||||
used. [The full version is here](browser-use-detection.md).
|
||||
|
||||
## Stagehand
|
||||
@@ -77,7 +77,7 @@ used. [The full version is here](browser-use-detection.md).
|
||||
Exposes `executablePath` and documents it, which is more than most. The rest of the
|
||||
codebase is CDP: local CDP discovery, CDP tailing, a CDP client. Chromium references
|
||||
outnumber Firefox ones by a wide margin, and the Firefox mentions are in an OpenAPI
|
||||
schema and a client for someone else's API rather than in a launch path.
|
||||
schema and a client for someone else's API, not in a launch path.
|
||||
|
||||
So the option exists and it expects a Chromium build.
|
||||
|
||||
@@ -97,7 +97,7 @@ documentation notes does not support Firefox, so that combination is largely ine
|
||||
## Maxun
|
||||
|
||||
Playwright is in the manifest and no executable path is exposed. As a no-code platform
|
||||
that is a coherent product decision rather than an oversight.
|
||||
that is a coherent product decision instead of an oversight.
|
||||
|
||||
## What applies regardless of the engine
|
||||
|
||||
@@ -224,7 +224,7 @@ this whole page is about.
|
||||
one. Pick on the agent loop, then fix the machine, then consider the engine.
|
||||
|
||||
**Is there any agent route to an engine-level fingerprint?** Two, and they are not
|
||||
equivalent. `uvx invisible-playwright-mcp` launches through the engine, so the
|
||||
equivalent. `uvx aihawk` launches through the engine, so the
|
||||
seeded profile and the humanised pointer come with it. Microsoft's own Playwright
|
||||
MCP server takes a browser and an executable path, which runs the engine but
|
||||
carries no `firefox_user_prefs`, so every session on a given build shares one
|
||||
|
||||
@@ -15,7 +15,7 @@ payload, and a server-side model combines that payload with the request's networ
|
||||
fingerprint into a Bot Score from 0 (human) to 100 (bot). Passing one layer of that
|
||||
pipeline, even the hardest layer, does not mean you pass the rest.
|
||||
|
||||
A real, documented case makes that concrete rather than theoretical. In April 2026 a
|
||||
A real, documented case makes that concrete, not theoretical. In April 2026 a
|
||||
user of [Camoufox](https://github.com/daijro/camoufox), a separate open-source project
|
||||
that also patches Firefox at the C++ level for automation, filed
|
||||
[an issue](https://github.com/daijro/camoufox/issues/555) reporting that an
|
||||
@@ -112,7 +112,7 @@ It does not remove the other six.
|
||||
|
||||
## The case that shows "matching fingerprint" is not "passing"
|
||||
|
||||
Here is what the GitHub issue actually contains, read directly rather than summarized
|
||||
Here is what the GitHub issue actually contains, read directly, not summarized
|
||||
from memory.
|
||||
|
||||
The reporter, running Camoufox v135.0.1-beta.24 through Playwright 1.58.0 on Linux, was
|
||||
|
||||
@@ -9,7 +9,7 @@ nav_order: 34
|
||||
|
||||
# Anubis: The Proof-of-Work Firewall, Explained
|
||||
|
||||
Every other vendor on this list is a commercial product whose internals have to be pieced together from reverse engineering, because the company that built it has no reason to publish them. Anubis is different: it is MIT-licensed, its full source is on GitHub, and its author writes publicly about why it exists and what it does not solve. This page is built almost entirely from primary material, its own repository, its own documentation, and a named security researcher's own published analysis, rather than practitioner reconstruction. Say that plainly, because it is the exception in this corpus, not the rule.
|
||||
Every other vendor on this list is a commercial product whose internals have to be pieced together from reverse engineering, because the company that built it has no reason to publish them. Anubis is different: it is MIT-licensed, its full source is on GitHub, and its author writes publicly about why it exists and what it does not solve. This page is built almost entirely from primary material, its own repository, its own documentation, and a named security researcher's own published analysis, not practitioner reconstruction. Say that plainly, because it is the exception in this corpus, not the rule.
|
||||
|
||||
Anubis was created by Xe Iaso, a pseudonymous developer, in January 2025, after Amazon's web crawler overloaded Iaso's own Git server while ignoring `robots.txt` entirely. It is now maintained by Techaro. The name is the joke and the mechanic at once: Anubis, the Egyptian god who weighs the hearts of the dead, and the software "weighs the soul" of an incoming HTTP request before deciding whether it deserves to reach the backend at all.
|
||||
|
||||
|
||||
@@ -17,9 +17,9 @@ This is one of the vendors in this corpus closer to an actual CAPTCHA than to a
|
||||
|
||||
## What Arkose's own materials say, and where they stop
|
||||
|
||||
Arkose's own public site describes its detection in terms of scale and adaptivity rather than mechanism: "225+ risk signals," "dynamic challenges that evolve in real time to counter emerging attack vectors," and device identification that combines "deterministic methods with machine learning similarity detection." Its own numbers past that point are business outcomes, not technical detail, customer satisfaction figures, dollar savings, account-growth multipliers, not the field names or scoring weights behind the 225 signals.
|
||||
Arkose's own public site describes its detection in terms of scale and adaptivity, not mechanism: "225+ risk signals," "dynamic challenges that evolve in real time to counter emerging attack vectors," and device identification that combines "deterministic methods with machine learning similarity detection." Its own numbers past that point are business outcomes, not technical detail, customer satisfaction figures, dollar savings, account-growth multipliers, not the field names or scoring weights behind the 225 signals.
|
||||
|
||||
That is a real limit on what this page can say with a straight face. Arkose does not publish, in the materials checked for this page, the specific list of what those 225+ signals are or how the risk engine weighs them. What follows past this point comes from independent, practitioner-level reverse engineering rather than Arkose's own documentation, and is marked as such.
|
||||
That is a real limit on what this page can say with a straight face. Arkose does not publish, in the materials checked for this page, the specific list of what those 225+ signals are or how the risk engine weighs them. What follows past this point comes from independent, practitioner-level reverse engineering, not Arkose's own documentation, and is marked as such.
|
||||
|
||||
## What practitioner reverse engineering has converged on
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ install. Its own documentation describes it plainly:
|
||||
> encapsulate a connection to an IMAP4 server and implement a large subset of the
|
||||
> IMAP4rev1 client protocol as defined in RFC 3501."
|
||||
|
||||
Use `IMAP4_SSL` for the connection, and pass an explicit SSL context rather than the
|
||||
Use `IMAP4_SSL` for the connection, and pass an explicit SSL context instead of the
|
||||
default one - the standard library is direct about why:
|
||||
|
||||
> "With the default ssl_context, the connection is encrypted but the server certificate
|
||||
|
||||
@@ -9,7 +9,7 @@ nav_order: 33
|
||||
|
||||
# AWS WAF Bot Control, Explained
|
||||
|
||||
AWS WAF Bot Control is a managed rule group, not a separate product with its own dashboard and SDK ecosystem the way Akamai or DataDome ship one. You add it to a Web ACL (AWS's term for a firewall policy) the same way you'd add any other managed rule group, and unlike most of the vendors in this corpus, AWS documents its rules by name, in public, with what each one inspects and what action it takes by default. That is unusually specific for this category, and this page leans on it: almost everything below is quoted or closely paraphrased from AWS's own developer guide rather than reconstructed from outside reverse engineering.
|
||||
AWS WAF Bot Control is a managed rule group, not a separate product with its own dashboard and SDK ecosystem the way Akamai or DataDome ship one. You add it to a Web ACL (AWS's term for a firewall policy) the same way you'd add any other managed rule group, and unlike most of the vendors in this corpus, AWS documents its rules by name, in public, with what each one inspects and what action it takes by default. That is unusually specific for this category, and this page leans on it: almost everything below is quoted or closely paraphrased from AWS's own developer guide, not reconstructed from outside reverse engineering.
|
||||
|
||||
Read from AWS's own documentation on 2026-08-30.
|
||||
|
||||
@@ -25,7 +25,7 @@ Two sub-families of targeted rules are named directly by their prefix. Rules beg
|
||||
|
||||
## The token: what ties a session's evidence together
|
||||
|
||||
Targeted detection runs on a **token**, generated by the JavaScript or mobile SDK and carried on subsequent requests, and AWS's rules read the token's state rather than re-deriving everything from scratch on every request. Two labels attached to every token matter most:
|
||||
Targeted detection runs on a **token**, generated by the JavaScript or mobile SDK and carried on subsequent requests, and AWS's rules read the token's state instead of re-deriving everything from scratch on every request. Two labels attached to every token matter most:
|
||||
|
||||
- `awswaf:managed:token:id:{{identifier}}`, a session identifier tied to the specific token in use, changing if the client acquires a new one.
|
||||
- `awswaf:managed:token:fingerprint:{{fingerprint-identifier}}`, a browser fingerprint AWS computes from client signals, which "stays the same across multiple token acquisition attempts" and is explicitly "not unique to a single client," AWS's own words for a value meant to identify a device class, not a specific visitor.
|
||||
@@ -34,7 +34,7 @@ A token can be `accepted` (present, with a valid, unexpired challenge or CAPTCHA
|
||||
|
||||
## What the individual rules actually check
|
||||
|
||||
A sample of named rules, quoted from AWS's own rule listing, gives a concrete sense of what "browser interrogation" and "behavior heuristics" mean in practice rather than as marketing language:
|
||||
A sample of named rules, quoted from AWS's own rule listing, gives a concrete sense of what "browser interrogation" and "behavior heuristics" mean in practice, not as marketing language:
|
||||
|
||||
| Rule | What it inspects | Default action |
|
||||
|---|---|---|
|
||||
@@ -50,11 +50,11 @@ A sample of named rules, quoted from AWS's own rule listing, gives a concrete se
|
||||
|
||||
The token-reuse family is worth pausing on: it does not ask whether any single request looks automated, it asks whether one browser's proof-of-legitimacy is being shared across more devices, networks or countries than a single real session plausibly touches in five minutes. That is a detection axis with no fingerprint answer at all, honest or otherwise, because the thing being scored is reuse across sessions, not any property of one session's browser.
|
||||
|
||||
AWS is also explicit about a category it treats differently from everything above: a maintained list of verified bots (search engine crawlers, monitoring services, SEO tools) that Bot Control identifies and does not block, adding a `bot:verified` label plus category and organization labels instead. A newer addition, **Web Bot Authentication**, lets a bot cryptographically sign its requests against a public key directory; a verified signature (`web_bot_auth:verified`) causes the category-block and `TGT_TokenAbsent` rules to skip that request entirely, a mechanism for bots that want to identify themselves honestly and be let through rather than evade detection.
|
||||
AWS is also explicit about a category it treats differently from everything above: a maintained list of verified bots (search engine crawlers, monitoring services, SEO tools) that Bot Control identifies and does not block, adding a `bot:verified` label plus category and organization labels instead. A newer addition, **Web Bot Authentication**, lets a bot cryptographically sign its requests against a public key directory; a verified signature (`web_bot_auth:verified`) causes the category-block and `TGT_TokenAbsent` rules to skip that request entirely, a mechanism for bots that want to identify themselves honestly and be let through, not evade detection.
|
||||
|
||||
## What an engine answers honestly, and what a browser cannot touch
|
||||
|
||||
`SignalAutomatedBrowser`, `TGT_SignalBrowserAutomationExtension`, and `TGT_SignalBrowserInconsistency` are the rules a real, engine-level browser answers by construction: a genuinely real Firefox, patched below the JavaScript layer rather than scripted from a content script, does not carry automation-framework tells, does not have a Selenium-style extension installed, and does not produce internally inconsistent browser-interrogation data, because nothing is faking any of those signals from the inside. That is the same argument this corpus makes for [BotD](botd-explained.md) and [CreepJS](creepjs-explained.md), applied to a managed rule group instead of an open-source script.
|
||||
`SignalAutomatedBrowser`, `TGT_SignalBrowserAutomationExtension`, and `TGT_SignalBrowserInconsistency` are the rules a real, engine-level browser answers by construction: a genuinely real Firefox, patched below the JavaScript layer, not scripted from a content script, does not carry automation-framework tells, does not have a Selenium-style extension installed, and does not produce internally inconsistent browser-interrogation data, because nothing is faking any of those signals from the inside. That is the same argument this corpus makes for [BotD](botd-explained.md) and [CreepJS](creepjs-explained.md), applied to a managed rule group instead of an open-source script.
|
||||
|
||||
Several rule families sit entirely outside what any browser engine can affect. `SignalKnownBotDataCenter` and the cloud-service-provider signal read the network origin, not the browser. The `TGT_VolumetricSession` and `TGT_TokenReuseIp/Country/Asn` families score session and token behavior across time and across requests, a property of how the automation is orchestrated (how many machines, how many networks, how fast) rather than of the browser rendering any one page. And `TGT_ML_CoordinatedActivity`, by AWS's own description, runs on aggregate traffic statistics across a site's whole visitor population, comparing against a baseline no single session's engine fidelity can influence.
|
||||
|
||||
|
||||
@@ -41,13 +41,13 @@ internally consistent identity per session - GPU, canvas, audio, fonts, screen,
|
||||
concrete things move:
|
||||
|
||||
- **The engine the screenshots come from.** The pixels the model sees are rendered by a
|
||||
browser whose fingerprint, TLS handshake and driver layer read as a genuine Firefox
|
||||
rather than as an automation build announcing itself. This is why it clears most
|
||||
browser whose fingerprint, TLS handshake and driver layer read as a genuine Firefox,
|
||||
not as an automation build announcing itself. This is why it clears most
|
||||
fingerprint, TLS and driver-layer checks: it is built to look like a real browser
|
||||
driven by a real person, not to suppress signals. A suppressed or blank surface is its
|
||||
own tell, so the goal is a present, plausible value, not a missing one.
|
||||
- **The page the clicks land on.** Coordinate clicks arrive on a page inside that engine,
|
||||
and pointer motion between them follows a Bezier curve rather than teleporting from
|
||||
and pointer motion between them follows a Bezier curve instead of teleporting from
|
||||
point to point.
|
||||
|
||||
What it does not touch is equally important, and the next section is about that.
|
||||
|
||||
@@ -20,7 +20,7 @@ That single fact turns the Battery API into a small but reliable consistency che
|
||||
page that claims to be Firefox in its user agent, and then successfully obtains a
|
||||
battery object, has not measured your battery. It has caught a browser that is lying
|
||||
about what it is. This page explains why that happens, why the honest answer is to have
|
||||
no Battery API rather than a convincing fake one, and how a genuine Firefox build gets
|
||||
no Battery API instead of a convincing fake one, and how a genuine Firefox build gets
|
||||
that for free.
|
||||
|
||||
## What the Battery Status API was, and why Firefox dropped it
|
||||
|
||||
@@ -35,7 +35,7 @@ look. Line them up and the confusion evaporates:
|
||||
belongs to the same visitor as before. It is about linkability, not about looking
|
||||
automated.
|
||||
- **A reCAPTCHA v3 score** is a risk estimate between 0.0 and 1.0, built mostly from
|
||||
behaviour and reputation rather than from what the DOM reports at all.
|
||||
behaviour and reputation, not from what the DOM reports at all.
|
||||
|
||||
| Number | The question it answers | What it reads | What moves it |
|
||||
|---|---|---|---|
|
||||
|
||||
@@ -65,7 +65,7 @@ most of why people get confused.
|
||||
- **ClientRects.** Reads the sub-pixel bounding boxes of positioned elements with
|
||||
[`getClientRects()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getClientRects).
|
||||
Like canvas, the exact fractional geometry varies with the
|
||||
rendering stack, so it is a fingerprint rather than a setting.
|
||||
rendering stack, so it is a fingerprint instead of a setting.
|
||||
|
||||
There are more pages - TLS, HTTP headers, geolocation, DNS - but these five are the ones
|
||||
people arrive worried about, and they are all raw-value readouts with no cross-check
|
||||
|
||||
@@ -71,13 +71,13 @@ something isn't in its bundle-only list, and each of those defaults quietly reac
|
||||
the host if you don't close it explicitly:
|
||||
|
||||
- One backend's safety fallback, when the bundle is unreadable, is to fail toward an
|
||||
empty list rather than the host - which breaks rendering visibly instead of leaking
|
||||
empty list instead of the host - which breaks rendering visibly instead of leaking
|
||||
silently, the correct failure direction for a fingerprinting surface.
|
||||
- Another's default path, taken naively, falls straight through to a live host
|
||||
enumeration call the moment the bundle-only condition isn't satisfied.
|
||||
- The third had no bundle-only mode at all going in; it enumerates host and bundled
|
||||
fonts through the same single API call, so keeping the host out requires filtering
|
||||
every result rather than skipping a call.
|
||||
every result instead of skipping a call.
|
||||
|
||||
Closing all three took a different patch per backend, because "don't enumerate the
|
||||
host" means something different to DirectWrite, to fontconfig, and to CoreText. There
|
||||
@@ -89,7 +89,7 @@ CoreText's version of this fix shipped later than Windows' and Linux's, and not
|
||||
because it was harder to write. It was harder to *know was wrong*, because nobody
|
||||
doing the work had a Mac to run it on.
|
||||
|
||||
**Layer one, found by reading the code rather than running it:** the block-at-birth
|
||||
**Layer one, found by reading the code instead of running it:** the block-at-birth
|
||||
hook that stops each backend from falling back to a live host enumeration had been
|
||||
wired into the Windows and Linux font backends, and simply never ported to CoreText.
|
||||
Reading the three backends side by side made that omission visible without running
|
||||
@@ -108,7 +108,7 @@ built in. A hook that is correct and a build that never includes it produce the
|
||||
observed nothing.
|
||||
|
||||
Both layers are closed now, and CoreText enumerates the identical family set the
|
||||
other two backends do. The reason this is worth telling as one story rather than two
|
||||
other two backends do. The reason this is worth telling as one story, not two
|
||||
separate fixes: the first fix looked complete by every check available without a
|
||||
real Mac, and was not. The only thing that caught the second layer was an automated
|
||||
run on the actual operating system, checking the actual output, after the fix that
|
||||
@@ -122,18 +122,18 @@ bundle, zero host fonts leaking through on either,
|
||||
[generic CSS families](https://www.w3.org/TR/css-fonts-4/) (serif, sans,
|
||||
monospace, and the per-script CJK generics) resolving to the same bundled fonts rather
|
||||
than collapsing to whatever the host happens to have. The same check on macOS runs in
|
||||
CI rather than locally, for the ordinary reason that not every setup has a Mac to test
|
||||
CI, not locally, for the ordinary reason that not every setup has a Mac to test
|
||||
on, and it has passed there too.
|
||||
|
||||
The cost is real and worth naming rather than glossing over. The binary is
|
||||
meaningfully larger, because it now carries real font files rather than relying on
|
||||
The cost is real and worth naming instead of glossing over. The binary is
|
||||
meaningfully larger, because it now carries real font files instead of relying on
|
||||
whatever the OS already had installed. And a fixed bundle also fixes the family list
|
||||
in time: unlike a live host, the browser cannot pick up a font a real Windows Update
|
||||
might add later. Both are the price of an answer that has no per-platform seams to find.
|
||||
|
||||
## Where it still leaks, named rather than hidden
|
||||
## Where it still leaks, named, not hidden
|
||||
|
||||
Consistent with treating a suppressed signal as a fail rather than a pass, the honest
|
||||
Consistent with treating a suppressed signal as a fail instead of a pass, the honest
|
||||
gaps in this approach, found and not yet closed:
|
||||
|
||||
- One backend's [CSS `local()`](https://www.w3.org/TR/css-fonts-4/) font lookup path
|
||||
|
||||
@@ -54,7 +54,7 @@ string](https://developer.mozilla.org/en-US/docs/Web/API/WEBGL_debug_renderer_in
|
||||
says so in plain text: a basic or generic renderer name, or the well-known software
|
||||
rasterizer strings. A real desktop reports a specific GPU model from a specific vendor.
|
||||
This is the single loudest VM tell
|
||||
in the browser, because it is a string you can read directly rather than a statistic
|
||||
in the browser, because it is a string you can read directly instead of a statistic
|
||||
you have to accumulate.
|
||||
|
||||
Worse, the string and the pixels can disagree: a renderer that
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
---
|
||||
title: "Why the same canvas draws differently on Windows and Linux"
|
||||
description: "Canvas fingerprints differ across Windows and Linux because the rasteriser, font files, hinting and GPU path differ, not the canvas drawing code."
|
||||
parent: "Canvas, WebGL, Fonts and Audio"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 15
|
||||
---
|
||||
|
||||
|
||||
# Why the same canvas draws differently on Windows and Linux
|
||||
|
||||
Two machines running the exact same `fillText()` and `toDataURL()` calls can return
|
||||
different bytes. A canvas hash never measures the drawing code alone: it measures the
|
||||
text rasteriser, the actual font file behind that family name, the subpixel and
|
||||
hinting policy, and whether a GPU or a software path drew it. Change any one and the
|
||||
pixels change, with nothing wrong in the script itself.
|
||||
|
||||
## What actually differs, mechanically, between two operating systems
|
||||
|
||||
A `fillText()` call looks like one instruction, but several layers sit underneath it
|
||||
before a pixel comes back, and any one of them can move the output between two
|
||||
machines running the identical script.
|
||||
|
||||
### The text rasteriser and its hinting policy
|
||||
|
||||
Windows draws glyphs through DirectWrite, or the older GDI path; Linux desktops
|
||||
typically use FreeType, fed by fontconfig. Both decide, pixel by pixel, how much of
|
||||
each pixel a glyph edge covers, and that depends on the hinting level in force. A
|
||||
glyph spanning eleven and a half pixels gets rounded differently by rasterisers with
|
||||
different hinting rules, and the rounding shows up directly in the readback.
|
||||
|
||||
### Which font file actually backs the family name
|
||||
|
||||
`ctx.font = "16px Arial"` does not point at one universal file. On Windows it
|
||||
resolves to Microsoft's own Arial. On a Linux desktop without Microsoft's fonts
|
||||
installed, the same family name commonly falls back to a metric-compatible substitute
|
||||
such as Liberation Sans, matching Arial's advance widths but not its glyph outlines.
|
||||
Same request, same font name, a different file drawing every letter.
|
||||
|
||||
### Subpixel geometry and antialiasing
|
||||
|
||||
A desktop session with subpixel rendering on draws each glyph edge using a display's
|
||||
red, green and blue sub-elements, producing colour fringing invisible at normal
|
||||
viewing distance but visible in a raw pixel readback. A headless or virtualised
|
||||
environment usually falls back to plain grayscale antialiasing instead, since there
|
||||
is no subpixel layout to target. The glyph looks the same to a human; the bytes do
|
||||
not match.
|
||||
|
||||
### GPU-accelerated versus software rendering paths
|
||||
|
||||
Canvas content can be composited by the GPU or rasterised in software, and which path
|
||||
a machine takes depends on driver support. A software rasteriser and a
|
||||
GPU-accelerated one do not have to agree on sub-pixel rounding, so identical draw
|
||||
commands can differ by a handful of values before fonts even enter the picture.
|
||||
|
||||
## Why text is the least stable element on a canvas
|
||||
|
||||
Draw a plain filled rectangle and the pixel values are close to universal: a solid
|
||||
colour passes through a rasteriser mostly unchanged, so a flat-colour hash tends to
|
||||
agree across machines that disagree on everything else. Draw text instead, and every
|
||||
layer named above gets involved at once: rasteriser, font file, hinting, subpixel
|
||||
policy, GPU path. That is why a text-free canvas is far more stable across machines,
|
||||
and why fingerprinting scripts almost always put a mixed-case string on the probe
|
||||
canvas rather than a plain shape.
|
||||
|
||||
## A canvas hash is a platform tell as much as a machine tell
|
||||
|
||||
Because font rendering is tied so tightly to the operating system, a canvas hash
|
||||
carries platform information whether anyone intended it to.
|
||||
[Windows implies Segoe UI and a specific CJK set; a bare Linux desktop implies
|
||||
DejaVu and Liberation and little else](headless-fonts-differ.md), and text rendered
|
||||
through those two stacks does not converge. That gives a page a checkable claim
|
||||
rather than a rare value: a browser whose user agent says Windows, drawing text whose
|
||||
antialiasing looks like Linux's FreeType instead of Windows' DirectWrite, has
|
||||
contradicted itself, and the check needs only one sample of each platform, not a
|
||||
notion of "normal" in the abstract.
|
||||
|
||||
## What this project does about it, and what it does not
|
||||
|
||||
For the values a page can read back from a canvas, this project ties the output to
|
||||
the session's own seed rather than to whatever the host has, which is what lets [the
|
||||
same identity return the same canvas and WebGL hash on Windows and on
|
||||
Linux](canvas-webgl-cross-platform-consistency.md); [`measureText()`'s numeric fields
|
||||
get the same treatment through a different mechanism](measuretext-textmetrics-fingerprinting.md).
|
||||
That is a statement about what a page can observe, not a claim that the rendering
|
||||
pipeline was rewritten to erase itself: rasterisation here is real drawing, done by
|
||||
[a real, bundled font stack](bundled-fonts-cross-platform.md) rather than a
|
||||
substituted picture, which is why a screenshot still shows real text instead of
|
||||
noise. The honest limit: the fix covers only the readback calls a page can make
|
||||
today, and any new export path a future engine adds needs the same treatment first.
|
||||
|
||||
## Conclusion
|
||||
|
||||
A canvas hash is not a single number a browser decides to report. It is the visible
|
||||
output of a rasteriser, a font file, a hinting policy and a rendering path, four
|
||||
layers a stock browser never controls independently of its operating system. Text
|
||||
draws through all four at once, which is why a text-bearing canvas is the first
|
||||
readback worth checking when a hash looks wrong for the platform a session claims to
|
||||
be.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why does my canvas fingerprint differ between Windows and Linux?** The pixels come
|
||||
from the OS's rasteriser, its font files, its hinting and subpixel policy, and
|
||||
whether the GPU or software drew the glyph, not from the drawing code.
|
||||
|
||||
**Does the same drawing code produce the same canvas hash on every OS?** No, not on
|
||||
a stock browser. Identical calls run through a different rasteriser and font file on
|
||||
each platform, and the readback reflects that.
|
||||
|
||||
**Is a canvas fingerprint a browser tell or a platform tell?** Mostly a platform
|
||||
tell. Two browsers on the same OS, drawing the same text, agree far more closely
|
||||
than one browser does across two operating systems.
|
||||
|
||||
**Does removing text make the hash more stable?** Yes. Solid fills pass through a
|
||||
rasteriser largely unchanged, while text pulls in the font stack, hinting and
|
||||
subpixel geometry at once.
|
||||
|
||||
**Can a browser match its canvas hash to a claimed operating system exactly?** Only
|
||||
by controlling what a page reads back, since the render itself comes from whichever
|
||||
rasteriser and font files are actually installed.
|
||||
|
||||
**See also:** [canvas fingerprint noise and why per-call randomising
|
||||
fails](canvas-fingerprint-noise.md), [why a canvas fingerprint changes every
|
||||
run](canvas-fingerprint-changes-every-run.md), and [measureText and TextMetrics as a
|
||||
fingerprinting surface](measuretext-textmetrics-fingerprinting.md).
|
||||
|
||||
## Sources
|
||||
|
||||
- [MDN: `CanvasRenderingContext2D.fillText()`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillText),
|
||||
[MDN: `HTMLCanvasElement.toDataURL()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL)
|
||||
and [MDN: `CanvasRenderingContext2D.getImageData()`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData),
|
||||
for the calls above.
|
||||
- MDN, `CanvasRenderingContext2D.measureText()`,
|
||||
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText -
|
||||
it "returns a TextMetrics object that contains information about the measured text
|
||||
(such as its width, for example)", which is the surface this page's text argument rests
|
||||
on. Read 5 September 2026.
|
||||
- This project's own measurements on font rendering, font bundling and canvas
|
||||
readback, referenced via the linked pages on this wiki.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
a Firefox patched at the C++ level driven by stock Playwright. A canvas hash was never
|
||||
really about the canvas; it was always about everything underneath it.*
|
||||
@@ -8,7 +8,7 @@ nav_order: 3
|
||||
|
||||
# Chromium is not Chrome, and detectors know the difference
|
||||
|
||||
**Short answer:** no, they are not the same, and the gap moved in 2026 rather than closing.
|
||||
**Short answer:** no, they are not the same, and the gap moved in 2026 instead of closing.
|
||||
Playwright's default Chromium - Chrome for Testing since v1.57 - now plays the same
|
||||
H.264/AAC codecs as real Chrome, checked directly in a live session. It still fails
|
||||
Chrome's [Widevine DRM check](https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API), and that part cannot be patched from JavaScript because it is
|
||||
@@ -20,16 +20,16 @@ The gap is real, it moved in 2026, and one part of it is still a **compiled-in c
|
||||
that a page can test for directly and that no amount of JavaScript patching can produce.
|
||||
|
||||
This page is what Playwright actually ships today, what changed and what didn't, why the
|
||||
part that remains cannot be patched, why spoofing the user agent makes it worse rather than
|
||||
part that remains cannot be patched, why spoofing the user agent makes it worse, not
|
||||
better, and why Firefox has no equivalent gap.
|
||||
|
||||
## What Playwright ships today, checked directly rather than assumed
|
||||
## What Playwright ships today, checked directly, not assumed
|
||||
|
||||
Playwright's own browser documentation used to be the whole answer: the default managed
|
||||
Chromium was an open-source build, missing the proprietary parts Google adds on top. As of
|
||||
[Playwright 1.57](https://playwright.dev/docs/release-notes), that changed. The default managed binary - launched with no `channel` set
|
||||
at all - is now **Chrome for Testing**, Google's own dedicated distribution for automated
|
||||
testing, pinned to the Playwright version rather than auto-updating.
|
||||
testing, pinned to the Playwright version instead of auto-updating.
|
||||
|
||||
Chrome for Testing is not the stripped-down build the old default was. It ships the same
|
||||
proprietary codec support as the Chrome a real visitor runs. Checked directly, in a live
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
---
|
||||
title: "Closed shadow roots: what Playwright cannot see"
|
||||
description: "Stock Playwright finds nothing inside a closed shadow root, in Firefox and Chromium alike. Measured, with the page that reproduces it and what this engine does instead."
|
||||
parent: "The Automation Layer"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 45
|
||||
---
|
||||
|
||||
|
||||
# Closed shadow roots: what Playwright cannot see
|
||||
|
||||
A closed shadow root makes `element.shadowRoot` return `null`, and stock
|
||||
Playwright locators stop at that boundary: measured on 5 September 2026
|
||||
against a page with one open and one closed root, stock Firefox and stock
|
||||
Chromium both matched the open content and returned zero matches for the
|
||||
closed content. The engine this wiki documents returns one match for the
|
||||
same closed content, and the page still reads `null`.
|
||||
|
||||
For the ordinary case, open shadow roots, Playwright crosses them by itself
|
||||
and there is nothing to configure: see
|
||||
[how to scrape shadow DOM content with Playwright](how-to-scrape-shadow-dom-playwright.md).
|
||||
This page is about the other case, and it starts with a number rather than
|
||||
an opinion.
|
||||
|
||||
## The measurement, and the page that reproduces it
|
||||
|
||||
The test page defines two custom elements. One attaches its shadow root with
|
||||
`mode: "open"`, the other with `mode: "closed"`, and each puts a unique
|
||||
string inside. Served from `127.0.0.1`, so no network variability, and the
|
||||
same file for every arm.
|
||||
|
||||
```html
|
||||
<open-widget></open-widget>
|
||||
<closed-widget></closed-widget>
|
||||
<script>
|
||||
class OpenWidget extends HTMLElement {
|
||||
connectedCallback() {
|
||||
const r = this.attachShadow({mode: "open"});
|
||||
r.innerHTML = '<p id="inner-open">OPEN_SECRET_VALUE_7788</p>';
|
||||
}
|
||||
}
|
||||
class ClosedWidget extends HTMLElement {
|
||||
connectedCallback() {
|
||||
const r = this.attachShadow({mode: "closed"});
|
||||
r.innerHTML = '<p id="inner-closed">CLOSED_SECRET_VALUE_9911</p>';
|
||||
this.readIt = () => r.querySelector("#inner-closed").textContent;
|
||||
}
|
||||
}
|
||||
customElements.define("open-widget", OpenWidget);
|
||||
customElements.define("closed-widget", ClosedWidget);
|
||||
</script>
|
||||
```
|
||||
|
||||
Three arms, one instrument, same page:
|
||||
|
||||
| arm | `#inner-open` | `#inner-closed` | text inside the closed root | `closed.shadowRoot` |
|
||||
|---|---|---|---|---|
|
||||
| Playwright, stock Firefox | 1 match | 0 matches | 0 matches | `null` |
|
||||
| Playwright, stock Chromium | 1 match | 0 matches | 0 matches | `null` |
|
||||
| Playwright, this engine | 1 match | **1 match** | **1 match** | `null` |
|
||||
|
||||
The stock rows are exactly what Playwright's own documentation promises:
|
||||
"Closed-mode shadow roots are not supported." The third row is this engine,
|
||||
and the last column is the part that matters most: from the page's point of
|
||||
view nothing changed. `element.shadowRoot` still reads `null`, because the
|
||||
resolution happens beneath the page's JavaScript rather than by rewriting
|
||||
what the page can see.
|
||||
|
||||
## Why the boundary exists at all
|
||||
|
||||
`attachShadow({ mode: "closed" })` is defined to hide the subtree from
|
||||
outside code. MDN puts it plainly: elements inside the shadow root "cannot
|
||||
be accessed from JavaScript via the `shadowRoot` property, which is set to
|
||||
`null`". The mode does not hide anything from the component itself, because
|
||||
`attachShadow()` returns the root to the code that called it, and that code
|
||||
keeps the reference for the life of the page.
|
||||
|
||||
So a closed root is an encapsulation choice by the component author, not a
|
||||
protection against automation, and it is not a detection surface either.
|
||||
Nothing about a closed root tells a site who is visiting.
|
||||
|
||||
## How to recognise one in ten seconds
|
||||
|
||||
Three signals together, never one alone. The element renders visible
|
||||
content. A selector aimed inside it returns nothing. And the host's
|
||||
`.shadowRoot`, read from the console, comes back `null`.
|
||||
|
||||
That last signal does not separate a closed root from an element with no
|
||||
shadow root at all. Pair it with the host's own `textContent`: on our test
|
||||
page the closed host returns an empty string while text is plainly on
|
||||
screen, which is the tell. Content you can see, text you cannot read from
|
||||
the host, and a `null` shadow root is a closed root every time.
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("http://127.0.0.1:8731/page.html")
|
||||
|
||||
host = page.query_selector("closed-widget")
|
||||
print(host.evaluate("el => el.shadowRoot !== null")) # False: null, as the spec says
|
||||
print(host.evaluate("el => el.textContent")) # '' while text is on screen
|
||||
print(page.locator("#inner-closed").count()) # 1 on this engine, 0 on stock
|
||||
```
|
||||
|
||||
## What still works when a selector will not reach
|
||||
|
||||
On stock Playwright the closed subtree is off limits to selectors, and
|
||||
three routes remain, each for a different reason.
|
||||
|
||||
The component's own script keeps full access, so any interface the author
|
||||
deliberately exposed on the host still answers. On the test page above the
|
||||
component sets a `readIt()` method on its host, and `page.evaluate` calling
|
||||
that method returned the closed string on every arm, stock included. A well
|
||||
built component publishes properties, methods, or events dispatched with
|
||||
`composed: true`, and that public surface is the door the author intended.
|
||||
|
||||
Input reaches the component regardless. The host sits in ordinary light DOM,
|
||||
so it has a real bounding box, it can be clicked, and keyboard focus moves
|
||||
into the controls inside it. Neither route lets you name what you are
|
||||
touching, but both reach it.
|
||||
|
||||
And the data usually exists before the component renders it. Most closed
|
||||
components are filled from a network response, and
|
||||
[waiting for that response](wait-for-specific-api-response-playwright.md)
|
||||
sidesteps the rendered tree entirely.
|
||||
|
||||
## The workaround that is worse than the problem
|
||||
|
||||
You will find snippets that patch `Element.prototype.attachShadow` before
|
||||
the page's scripts run so every later call becomes `mode: "open"`. It has
|
||||
two problems. It only wins a timing race you rarely control, and it changes
|
||||
what the page itself can observe: after the patch, `element.shadowRoot`
|
||||
stops being `null` on components whose authors asked for `null`. That is a
|
||||
difference a consistency check can read, which is the opposite of the goal
|
||||
on a wiki like this one.
|
||||
|
||||
The measurement above is the argument against it. Reaching the content while
|
||||
leaving `shadowRoot` at `null` is strictly better than reaching it by making
|
||||
the page lie about itself.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why does my Playwright locator find nothing when the element is visible?**
|
||||
If the host's `.shadowRoot` reads `null` while text renders on screen, the
|
||||
content is inside a closed shadow root. Stock Playwright locators stop
|
||||
there, in Firefox and Chromium alike.
|
||||
|
||||
**Does Playwright support closed shadow roots?** No. Its documentation says
|
||||
so directly, and the measurement above confirms it on both stock engines:
|
||||
zero matches for content that is plainly rendered.
|
||||
|
||||
**How do I tell an open root from a closed one?** Read `element.shadowRoot`.
|
||||
An object means open. `null` means closed, or no shadow root at all, and the
|
||||
host's empty `textContent` next to visible text separates those two.
|
||||
|
||||
**Can I force a closed root open?** You can patch `attachShadow` before the
|
||||
component runs, and you should not. It depends on a race you do not control
|
||||
and it changes what the page can observe about itself.
|
||||
|
||||
**What if the data only exists inside a closed root?** Call whatever the
|
||||
component exposes on its host, or read the network response that filled it.
|
||||
On this engine, a locator also reaches the content directly.
|
||||
|
||||
**See also:** [scraping open shadow DOM with Playwright](how-to-scrape-shadow-dom-playwright.md),
|
||||
[scraping iframe content with Playwright](how-to-scrape-iframe-content-playwright.md),
|
||||
and [waiting for a specific API response](wait-for-specific-api-response-playwright.md).
|
||||
|
||||
## Sources
|
||||
|
||||
- MDN, `Element.attachShadow()`,
|
||||
https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow -
|
||||
the `closed` mode definition and the quoted sentence about `shadowRoot`
|
||||
being set to `null`. Read 5 September 2026.
|
||||
- Playwright, Locators,
|
||||
https://playwright.dev/python/docs/locators - "All locators in Playwright
|
||||
by default work with elements in Shadow DOM" and "Closed-mode shadow roots
|
||||
are not supported". Read 5 September 2026.
|
||||
- Our own measurement, 5 September 2026: the page above served from
|
||||
`127.0.0.1`, run against stock Playwright Firefox, stock Playwright
|
||||
Chromium and this engine, same script for all three arms.
|
||||
|
||||
---
|
||||
|
||||
*From [invisible_playwright](https://github.com/feder-cr/invisible_playwright).
|
||||
The three-arm table is our own run and the test page is printed above so you
|
||||
can reproduce it rather than take our word for it.*
|
||||
@@ -25,7 +25,7 @@ The mechanism, per Cloudflare's own description, uses "Workers AI with an open s
|
||||
|
||||
**The content is real, but deliberately unrelated.** Cloudflare states the generated pages cover "scientific facts, just not relevant or proprietary to the site being crawled." It is not garbage text and not misinformation by design, it is genuine, coherent content that has nothing to do with the site a crawler thinks it is scraping, chosen specifically so the maze does not itself become a source of false claims circulating under someone else's domain.
|
||||
|
||||
**It is pre-generated, not created live per request.** Cloudflare's post describes "a pre-generation pipeline that sanitizes the content to prevent any XSS vulnerabilities," with pages stored (in Cloudflare's own infrastructure, via R2 object storage) rather than generated fresh for every hit. That is a performance and safety choice: generating unique HTML live for every crawler request at Cloudflare's traffic volume would be its own cost and attack surface, and pre-screening for injected script content closes an obvious way a maze of AI-generated pages could otherwise be turned against the very sites serving them.
|
||||
**It is pre-generated, not created live per request.** Cloudflare's post describes "a pre-generation pipeline that sanitizes the content to prevent any XSS vulnerabilities," with pages stored (in Cloudflare's own infrastructure, via R2 object storage), not generated fresh for every hit. That is a performance and safety choice: generating unique HTML live for every crawler request at Cloudflare's traffic volume would be its own cost and attack surface, and pre-screening for injected script content closes an obvious way a maze of AI-generated pages could otherwise be turned against the very sites serving them.
|
||||
|
||||
## It is also a honeypot, not just a delay tactic
|
||||
|
||||
|
||||
@@ -92,6 +92,8 @@ need rendering. Each page below states where the other tool covers more.
|
||||
- [invisible_playwright vs hrequests](vs-hrequests.md) - A hybrid TLS-impersonating HTTP client plus a browser mode with injected fingerprints.
|
||||
- [tls-client vs a real browser: when TLS is enough](vs-tls-client.md) - When JA3/HTTP2 socket spoofing suffices on JSON and HTML, and where JS forces a full browser.
|
||||
|
||||
- [invisible_playwright vs browser-use: different jobs](vs-browser-use.md) - An LLM-driven agent framework against an engine you drive yourself, and where each one fits.
|
||||
|
||||
## Unmaintained tools
|
||||
|
||||
- [puppeteer-extra-plugin-stealth: unmaintained since 2024](puppeteer-extra-stealth-unmaintained.md) - No real update since mid-2024; old patches still work but the checklist froze.
|
||||
|
||||
@@ -58,7 +58,7 @@ There are two different reasons you might reach for this flag, and only one of t
|
||||
survives contact with what the flag actually does.
|
||||
|
||||
**Legitimate testing need: your own code, your own CSP.** If you are testing a page you
|
||||
control and the point of the test is the page's functionality rather than its CSP
|
||||
control and the point of the test is the page's functionality instead of its CSP
|
||||
configuration, bypassing CSP to let your own instrumentation or a third-party testing
|
||||
widget run is a reasonable, disclosed tradeoff. You know the header is there, you know
|
||||
you are turning it off for the test, and the production page a real visitor loads still
|
||||
@@ -108,7 +108,7 @@ broader than most cases need.
|
||||
|
||||
**Known limitation:** documented reports exist of `bypassCSP` not resolving every CSP or
|
||||
CORS error depending on the specific directive and browser version, so confirm the
|
||||
console warning is actually gone after setting the option rather than assuming the flag
|
||||
console warning is actually gone after setting the option instead of assuming the flag
|
||||
is unconditionally comprehensive.
|
||||
|
||||
## Diagnostic checklist
|
||||
@@ -116,11 +116,11 @@ is unconditionally comprehensive.
|
||||
1. Check the browser console for a `Content-Security-Policy` message naming the refused
|
||||
directive before assuming your injection code is broken.
|
||||
2. Read the response's `content-security-policy` header directly to see the actual
|
||||
policy rather than guessing from the symptom.
|
||||
policy instead of guessing from the symptom.
|
||||
3. Confirm the refusal is `script-src` (or `default-src` covering it), not an unrelated
|
||||
directive that happens to also block something in your flow.
|
||||
4. Decide whether this is your own page under test or a third-party target, and apply
|
||||
the tradeoff above rather than reaching for `bypass_csp` reflexively.
|
||||
the tradeoff above instead of reaching for `bypass_csp` reflexively.
|
||||
5. After setting `bypass_csp=True`, re-check the console to confirm the specific warning
|
||||
is gone; a version-specific gap means it is not always comprehensive.
|
||||
|
||||
|
||||
@@ -67,16 +67,16 @@ Same source: DataDome states its engine processes on the order of three
|
||||
trillion signals a day (2022 figure). A separate 2026 write-up from
|
||||
Scrapfly, a scraping infrastructure vendor, cites five trillion a day and
|
||||
"over 85,000 customer-specific and use-case-specific models," one set per
|
||||
protected site rather than one global model. Four years apart and not
|
||||
protected site instead of one global model. Four years apart and not
|
||||
necessarily in tension, but neither figure is audited, so treat both as
|
||||
vendor reporting rather than something this page verified independently.
|
||||
vendor reporting, not something this page verified independently.
|
||||
|
||||
IP and ASN sit in the same layer conceptually: whether the address is
|
||||
residential, mobile or datacenter, its distance from the claimed timezone,
|
||||
how many recent requests share it. [What ASN and IP reputation actually
|
||||
score, and how fast it decays, is covered separately](asn-and-ip-reputation-in-bot-detection.md);
|
||||
DataDome's docs do not detail IP scoring, so this leans on the practitioner
|
||||
writeups rather than DataDome's own pages.
|
||||
writeups, not DataDome's own pages.
|
||||
|
||||
## The device check: what the JavaScript tag actually collects
|
||||
|
||||
@@ -114,7 +114,7 @@ lists, camera/microphone permission state, and two separate sets of
|
||||
User-Agent Client Hints. A vendor selling a bypass product has an obvious
|
||||
incentive to make its own reverse engineering sound thorough, so read this
|
||||
list as corroborated in outline, two unrelated writeups converge on canvas,
|
||||
WebGL, fonts and automation-framework checks, rather than verified line by
|
||||
WebGL, fonts and automation-framework checks, not verified line by
|
||||
line.
|
||||
|
||||
DataDome's own **Device Check** feature is the name for the invisible
|
||||
|
||||
@@ -94,7 +94,7 @@ consumer operating system, and that mismatch is the signal.
|
||||
|
||||
Claiming Windows in the user agent while the font vector is a Linux base image
|
||||
is a one-line contradiction, and it is exactly the kind of internal disagreement
|
||||
that [a browser that inspects consistency rather than values](how-to-test-bot-detection.md)
|
||||
that [a browser that inspects consistency, not values](how-to-test-bot-detection.md)
|
||||
records as a lie.
|
||||
|
||||
The same probe list produces a different vector in each of these three cases:
|
||||
|
||||
@@ -12,7 +12,7 @@ nav_order: 12
|
||||
No. A VPN changes one thing: the IP address the server sees. The browser
|
||||
fingerprint - canvas, WebGL, installed fonts, the user agent, the timezone, the
|
||||
hardware counters - is exactly what it was before you connected. Worse, a VPN can
|
||||
make a session look more suspicious rather than less, because it introduces a second
|
||||
make a session look more suspicious, not less, because it introduces a second
|
||||
story about where you are and gives a detector two stories to compare.
|
||||
|
||||
This page is what a VPN moves, what it leaves in place, the specific way it can
|
||||
@@ -35,7 +35,7 @@ different problem with a different owner.
|
||||
|
||||
## What a VPN leaves untouched
|
||||
|
||||
Open any fingerprinting report through a VPN and read the fields rather than the
|
||||
Open any fingerprinting report through a VPN and read the fields, not the
|
||||
verdict. The address at the top has changed. Nothing below it has:
|
||||
|
||||
- **[Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) and
|
||||
|
||||
@@ -18,7 +18,7 @@ not a launch-time argument Playwright resolves for you.
|
||||
|
||||
This gets asked because the Chromium path is well documented and looks like it should
|
||||
generalize, and because the honest answer involves a handful of old, still-open
|
||||
GitHub issues rather than a clean feature page. Here is what Playwright actually
|
||||
GitHub issues instead of a clean feature page. Here is what Playwright actually
|
||||
supports, what does not work, and the one route that does.
|
||||
|
||||
## What Playwright's documented extension support actually is
|
||||
|
||||
@@ -69,7 +69,7 @@ are consistency gaps: a headless context with no real GPU, a screen size no disp
|
||||
list or font set that does not match the claimed platform. Each is a small addition to the
|
||||
score, and together they are the fingerprint contribution.
|
||||
|
||||
You can see this contribution directly rather than taking it on faith. Open the same
|
||||
You can see this contribution directly instead of taking it on faith. Open the same
|
||||
detector page in your automated browser and in a stock browser on the same machine, and
|
||||
diff the reports field by field. The
|
||||
[method for doing that comparison honestly](how-to-test-bot-detection.md) is worth reading
|
||||
|
||||
@@ -125,7 +125,7 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
page.goto("https://example.com")
|
||||
|
||||
# what a text / accessibility-tree agent would hand to the model
|
||||
tree = page.accessibility.snapshot()
|
||||
tree = page.aria_snapshot()
|
||||
text = page.inner_text("body")
|
||||
|
||||
# the model returns an action against a selector
|
||||
@@ -148,7 +148,7 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
page.mouse.click(220, 140)
|
||||
```
|
||||
|
||||
The `browser` is a real Playwright `Browser`, so `accessibility.snapshot()`,
|
||||
The `browser` is a real Playwright `Browser`, so `aria_snapshot()`,
|
||||
`inner_text()`, [`screenshot()`](https://playwright.dev/python/docs/api/class-page#page-screenshot)
|
||||
and [`mouse.click()`](https://playwright.dev/python/docs/api/class-mouse#mouse-click) are
|
||||
all the standard upstream methods.
|
||||
|
||||
@@ -10,7 +10,7 @@ nav_order: 10
|
||||
# Emoji fingerprinting: why emoji look the same on any OS
|
||||
|
||||
Emoji look the same on any OS in Firefox because Firefox draws colour emoji from
|
||||
its own bundled font rather than the platform's, so the render is host-independent.
|
||||
its own bundled font instead of the platform's, so the render is host-independent.
|
||||
That is worth explaining, because emoji are otherwise one of the oldest
|
||||
operating-system tells there is. The same code point is drawn from a different font
|
||||
on each platform, and those fonts do not agree on a single pixel: Windows renders
|
||||
@@ -48,7 +48,7 @@ operating system's emoji font at all. It ships its own colour-emoji font, based
|
||||
Twemoji, inside the browser package, and it rasterises colour emoji from that
|
||||
bundled file on every platform it runs on. A stock Firefox on Windows, a stock
|
||||
Firefox on macOS and a stock Firefox on Linux all draw the same emoji from the
|
||||
same font, because the font travels with the browser rather than coming from the
|
||||
same font, because the font travels with the browser instead of coming from the
|
||||
host.
|
||||
|
||||
That is a structural difference from Chrome, which defers to the platform emoji
|
||||
@@ -63,7 +63,7 @@ assume. The engine has already made the render host-independent.
|
||||
This project builds on that property deliberately. To make text match Windows on
|
||||
any host, the build bundles a set of real Windows font files and exposes only
|
||||
those families, so a Linux server draws Latin, CJK and the rest from genuine
|
||||
Windows glyphs rather than from whatever the host happens to have installed. The
|
||||
Windows glyphs, not from whatever the host happens to have installed. The
|
||||
same idea is covered in detail under [bundled fonts that render the same on every OS](bundled-fonts-cross-platform.md).
|
||||
|
||||
The emoji font is treated differently, and on purpose. The colour-emoji file is
|
||||
|
||||
@@ -20,7 +20,7 @@ already worked.
|
||||
## The causes that are usually fine
|
||||
|
||||
**A download started instead of a page load.** When a navigation resolves to a file
|
||||
download rather than an HTML response, the browser aborts the page-level navigation
|
||||
download instead of an HTML response, the browser aborts the page-level navigation
|
||||
in favor of handing the response to the download machinery, and Playwright surfaces
|
||||
that abort as `net::ERR_ABORTED` even though the file saves correctly.
|
||||
[microsoft/playwright-java#541](https://github.com/microsoft/playwright-java/issues/541)
|
||||
|
||||
@@ -68,7 +68,7 @@ Wi-Fi, because the check that would have told them apart is the check you disabl
|
||||
|
||||
The narrower, safer alternative when the actual goal is trusting one specific proxy
|
||||
is installing that proxy's own root CA certificate into the browser's trust store,
|
||||
so only that one issuer becomes trusted rather than every issuer becoming
|
||||
so only that one issuer becomes trusted, not every issuer becoming
|
||||
irrelevant. Where that is not practical, the operationally honest habit is scoping
|
||||
`ignoreHTTPSErrors` to sessions that are genuinely, deliberately behind a proxy you
|
||||
control, never to a context whose traffic might also touch a network you do not
|
||||
|
||||
@@ -10,7 +10,7 @@ nav_order: 37
|
||||
# net::ERR_CONNECTION_REFUSED in Playwright
|
||||
|
||||
`net::ERR_CONNECTION_REFUSED` means the machine at the other end of the address and port
|
||||
actively refused the connection: it answered with a TCP reset rather than staying silent.
|
||||
actively refused the connection: it answered with a TCP reset instead of staying silent.
|
||||
Chromium's own network error list defines it in five words, "A connection attempt was
|
||||
refused," code -102. `page.goto()` throws it fast, usually in well under a second, because
|
||||
a refusal is an immediate reply, not a wait for something that never comes.
|
||||
@@ -27,7 +27,7 @@ on that exact port, or something is actively and deliberately rejecting the atte
|
||||
started, a service that crashed, or a port number that is simply wrong. Confirm the
|
||||
process is actually running and bound to the port you are navigating to.
|
||||
|
||||
**A firewall or security group actively rejecting rather than silently dropping.** Some
|
||||
**A firewall or security group actively rejecting, not silently dropping.** Some
|
||||
firewall configurations answer a blocked port with a reset (refused) and others simply
|
||||
drop the packet (timeout). Which one you get depends on the device, not on Playwright.
|
||||
|
||||
@@ -40,7 +40,7 @@ it enough time, headless did not.
|
||||
[A GitHub Actions report](https://github.com/microsoft/playwright/issues/21414) and
|
||||
[a CircleCI report](https://github.com/microsoft/playwright/issues/20343) both show
|
||||
`ERR_CONNECTION_REFUSED` against `localhost` reproducing reliably in CI and not locally,
|
||||
which is the signature of an environment-specific networking difference rather than a
|
||||
which is the signature of an environment-specific networking difference instead of a
|
||||
code regression.
|
||||
|
||||
## The Docker and CI networking variant, in detail
|
||||
@@ -65,8 +65,8 @@ instead, where nothing is listening, and gets refused. The same code works perfe
|
||||
developer's own machine, because there `localhost` genuinely is the machine running both
|
||||
the browser and the server, no namespace boundary in between, which is exactly why the
|
||||
bug reads as "nothing changed" when the entire network topology did. Port publishing
|
||||
(`-p 3000:3000`) does not fix this either if the server itself is bound to `127.0.0.1`
|
||||
rather than `0.0.0.0`: "the server is listening on 127.0.0.1 inside the container network
|
||||
(`-p 3000:3000`) does not fix this either if the server itself is bound to `127.0.0.1`,
|
||||
not `0.0.0.0`: "the server is listening on 127.0.0.1 inside the container network
|
||||
namespace" while the forwarded traffic arrives on the external interface, an address the
|
||||
server was never told to listen on. [A real report](https://github.com/microsoft/playwright/issues/24582)
|
||||
shows exactly this shape: the port listed as exposed in a Compose file, and the connection
|
||||
@@ -89,7 +89,7 @@ the equivalent Compose `extra_hosts` entry.
|
||||
Playwright's process, the target service, and your own terminal can each be in a
|
||||
different network namespace, each with its own idea of `localhost`.
|
||||
3. **Check what interface the target service binds to**, and address other Compose
|
||||
services by their service name rather than `localhost`, which does not cross
|
||||
services by their service name, not `localhost`, which does not cross
|
||||
container boundaries at all.
|
||||
4. **In CI specifically, test from inside the runner**, since a firewall or security
|
||||
group there can behave differently from your own machine even when the code and the
|
||||
|
||||
@@ -22,7 +22,7 @@ failure and not a handshake failure. Something answered the socket, then said no
|
||||
**A crashed or overloaded backend.** A worker process dying mid-request, an
|
||||
out-of-memory kill, or a request handler that raises before writing a single byte all
|
||||
leave the reverse proxy or load balancer in front of it holding an open connection with
|
||||
nothing to forward. The proxy closes the client connection rather than inventing a
|
||||
nothing to forward. The proxy closes the client connection instead of inventing a
|
||||
response, and the browser reports exactly this.
|
||||
|
||||
**A proxy or load balancer timing out on the backend and giving up without answering.**
|
||||
@@ -36,7 +36,7 @@ documented, ordinary feature of production web servers, not a theory about hosti
|
||||
intent. nginx's own status code `444` exists specifically to close a connection without
|
||||
sending any response, and the `reset_timedout_connection` directive, in nginx's own
|
||||
words, applies to "connections closed with the non-standard code 444," releasing the
|
||||
socket with a TCP reset rather than a normal close. A server operator who wants to deny
|
||||
socket with a TCP reset, not a normal close. A server operator who wants to deny
|
||||
a request with zero information leakage, whether the requester is a scanner, a bot, or
|
||||
simply unwanted traffic, has this as a first-class, standard option: return nothing
|
||||
rather than a status code that says "blocked."
|
||||
|
||||
@@ -40,7 +40,7 @@ not before a tunnel opened.
|
||||
Chromium's error list places several related, more specific failures right next to this
|
||||
one, and which one you actually see narrows the cause: `ERR_MISSING_AUTH_CREDENTIALS`
|
||||
(-341), "No Kerberos credentials were available during HTTP Authentication," the
|
||||
GSSAPI-specific case of having nothing to offer for a Negotiate challenge rather than
|
||||
GSSAPI-specific case of having nothing to offer for a Negotiate challenge instead of
|
||||
offering something that gets rejected; `ERR_UNSUPPORTED_AUTH_SCHEME` (-339), "An HTTP
|
||||
Authentication scheme was tried which is not supported on this machine," a platform gap
|
||||
rather than wrong credentials; and `ERR_MALFORMED_IDENTITY` (-329), "The identity used
|
||||
|
||||
@@ -42,7 +42,7 @@ on a failure that happens a step earlier than anything it controls.
|
||||
**A cipher suite or TLS version neither side supports.** The client offers a set of
|
||||
ciphers and protocol versions in its ClientHello; if the server's own configuration has
|
||||
no overlap with what was offered, at whatever versions each side is willing to speak,
|
||||
the handshake fails outright rather than falling back gracefully. This is common on
|
||||
the handshake fails outright instead of falling back gracefully. This is common on
|
||||
older or misconfigured servers, and on modern servers being reached by an outdated or
|
||||
deliberately restricted client.
|
||||
|
||||
@@ -66,7 +66,7 @@ reach.
|
||||
|
||||
**A port or scheme mismatch.** Requesting `https://` against a port actually serving
|
||||
plain HTTP, or the reverse, produces bytes that do not parse as the protocol either side
|
||||
expected, which surfaces as a protocol-level failure rather than a clean rejection.
|
||||
expected, which surfaces as a protocol-level failure, not a clean rejection.
|
||||
|
||||
**HTTP/3 or QUIC negotiation failing where HTTP/2 or HTTP/1.1 would have worked.**
|
||||
Cloudflare's own documentation names HTTP/3 incompatibility as a distinct cause
|
||||
@@ -90,7 +90,7 @@ forcing an older protocol.
|
||||
5. **Do not reach for `ignoreHTTPSErrors` first.** It has no effect on a handshake that
|
||||
never produced a certificate to evaluate; testing it and seeing no change, the way
|
||||
the real report above did, is itself useful confirmation the failure is
|
||||
protocol-level rather than trust-level.
|
||||
protocol-level, not trust-level.
|
||||
|
||||
## What Firefox reports instead
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ The collection code is not a plain script a browser's devtools can read line by
|
||||
|
||||
F5's own phrasing: "Bot Defense examines the telemetry collected from requests before they are permitted to reach your application." A bot detection rule, in F5's own terms, "contains criteria that Bot Defense uses to determine whether a transaction is from a human or automated source," and that determination is made before the origin server does anything with the request at all.
|
||||
|
||||
Two outcomes follow. For traffic Bot Defense calls human or an explicitly allowed automated source, "Bot Defense adds a custom HTTP request header to the request and allows the traffic to continue to the origin," which gives the origin application a signal it can check without having to run its own detection. For traffic it calls automated, the configured mitigation, monitor, block, or redirect, applies instead; F5's docs describe this as configurable per endpoint policy rather than a single global switch.
|
||||
Two outcomes follow. For traffic Bot Defense calls human or an explicitly allowed automated source, "Bot Defense adds a custom HTTP request header to the request and allows the traffic to continue to the origin," which gives the origin application a signal it can check without having to run its own detection. For traffic it calls automated, the configured mitigation, monitor, block, or redirect, applies instead; F5's docs describe this as configurable per endpoint policy instead of a single global switch.
|
||||
|
||||
## The 2020 shift, and what F5's newer material adds
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ Once loaded, the script's execution feeds three system signals a site owner can
|
||||
| Signal | What it indicates |
|
||||
|---|---|
|
||||
| `SUSPECTED-BOT.HEADLESS` | Probable headless browser activity |
|
||||
| `SUSPECTED-BAD-BOT.HEADLESS` | Headless activity Fastly's model treats as malicious rather than merely automated |
|
||||
| `SUSPECTED-BAD-BOT.HEADLESS` | Headless activity Fastly's model treats as malicious, not merely automated |
|
||||
| `CLIENTSIDE-COOKIE-VALID` | The client-side script ran and produced a cookie, i.e. it is a real, executing browser environment |
|
||||
|
||||
The cookie itself is named `_fs_cd_cp_` in Fastly's own docs, and its presence is how a site owner or a Fastly rule confirms the script actually executed rather than being blocked or skipped.
|
||||
@@ -47,7 +47,7 @@ Handling then splits by inspection point: pre-cache rules can act on a `fastly.b
|
||||
|
||||
## Signals beyond headless detection
|
||||
|
||||
Fastly's broader materials name additional categories without publishing the same level of implementation detail as the headless script: **client fingerprinting**, to "identify client types and detect bots designed for malicious activities," and **AI bot detection**, aimed specifically at "AI crawlers and fetchers" as their own traffic class. A 2024 addition, the `BOT-ANALYSIS` system signal, is documented only at the level of "a request that was analyzed for bots," without the finer distinctions Fastly gives the headless-specific signals; this page reports that limitation rather than guessing at what `BOT-ANALYSIS` adds beyond the headless triad.
|
||||
Fastly's broader materials name additional categories without publishing the same level of implementation detail as the headless script: **client fingerprinting**, to "identify client types and detect bots designed for malicious activities," and **AI bot detection**, aimed specifically at "AI crawlers and fetchers" as their own traffic class. A 2024 addition, the `BOT-ANALYSIS` system signal, is documented only at the level of "a request that was analyzed for bots," without the finer distinctions Fastly gives the headless-specific signals; this page reports that limitation instead of guessing at what `BOT-ANALYSIS` adds beyond the headless triad.
|
||||
|
||||
## What an engine answers honestly, and what stays server-side
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ your index is empty, but no amount of waiting for JavaScript fixes it, because t
|
||||
JavaScript was never allowed to run.
|
||||
|
||||
A real browser addresses both at once: it executes the page's JavaScript, and it makes a
|
||||
request that reads as a genuine Firefox rather than a script. That is the whole reason to
|
||||
request that reads as a genuine Firefox instead of a script. That is the whole reason to
|
||||
put a browser in front of the index instead of an HTTP loader.
|
||||
|
||||
## The fetch stage: render with a real browser fingerprint
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
title: "First Firefox launch fails on Windows, then works"
|
||||
description: "A freshly extracted Firefox can fail its very first launch on Windows and then succeed every time after. What we measured, why, and how to handle it."
|
||||
parent: "Testing and Troubleshooting"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 29
|
||||
---
|
||||
|
||||
|
||||
# First Firefox launch fails on Windows, then works
|
||||
|
||||
A freshly extracted Firefox directory can fail to launch on Windows on its very first attempt and then succeed every single time after, with no code change and no reinstall. We measured this directly: the failure tracks the executable's file path, not the directory's contents, and a Windows registry key tied to that path is the strongest lead we found.
|
||||
|
||||
## The symptom
|
||||
|
||||
Extract a Firefox build to a brand new path on Windows and launch it. Sometimes the launch fails immediately, with no window, no error dialog, and nothing useful beyond a bare launch timeout. Try again at the exact same path with the exact same binary, no changes at all, and it works. Not just once: every later launch at that same path succeeded, every time, in every test we ran.
|
||||
|
||||
The rate is not "every first launch fails." Most first launches at a new path succeed cleanly. When one does fail, though, it fails fast, in under a second, and the very next attempt at the identical path always worked in our testing.
|
||||
|
||||
## What we ruled out
|
||||
|
||||
Our first instinct was that the extracted directory itself was incomplete on that one run. It wasn't: we took a directory that had already launched successfully many times, copied it whole to a new path we'd never used, and its first launch there failed the same way, with byte-for-byte identical contents to a working copy elsewhere. We also ruled out the per-launch profile Playwright creates, clearing every cache we could find, and re-downloading the build from scratch. None of it made any measurable difference. Whatever was failing lived outside both the directory and the profile.
|
||||
|
||||
## What the registry key points to
|
||||
|
||||
Firefox's startup on Windows goes through a launcher stage before the browser process starts, keeping state outside the installation directory. We found a registry key, `HKCU\Software\Mozilla\Firefox\Launcher`, holding timestamped entries keyed by the executable's own file path. A path never launched before had no entry; the same path, launched again, did.
|
||||
|
||||
That correlation matches what we observed: new path, no entry, occasional immediate failure; same path again, entry present, no failure. Two halves of this are worth keeping apart. The launcher stage itself is documented by Mozilla: Firefox on Windows bootstraps through a launcher process that, unlike every other process in the browser, "is not launched by the parent process, but rather launches it", and it exists so that protections like DLL blocklisting are in place before the browser's main thread runs. Mozilla treats launcher failures as a real enough category to ship a telemetry ping for them. The registry key and its per-executable timestamps, on the other hand, are our own observation: we found them, we can read them, and we have not found Mozilla documentation that describes them, so treat that half as a measured correlation rather than an architectural claim.
|
||||
|
||||
## The process that dies is the launcher, not the browser
|
||||
|
||||
The detail worth carrying into your own debugging: the process that exits is the launcher, not the browser you're trying to drive. It exits within a fraction of a second and writes no log anywhere we looked. "The browser printed nothing" is the wrong way to describe it, because the browser was never created. From Playwright's side, a dead launcher looks exactly like a plain launch timeout, with none of the specifics that would point at what actually went wrong.
|
||||
|
||||
## How to recognise this specific failure
|
||||
|
||||
- It only happens on the first launch at a path you have never used before, never on a path you have already launched successfully.
|
||||
- It fails fast, typically well under a second, not after waiting out a timeout.
|
||||
- There is no log file and no window, even briefly.
|
||||
- Retrying the exact same launch, same path, same everything, succeeded the second time in every case we saw.
|
||||
|
||||
If your failure doesn't match this shape, slow rather than instant, or the same path failing on every attempt, you're looking at something else. [Slow browser launch: a per-request timeout is not a budget](slow-browser-launch-timeout-budget.md) and [Playwright "Executable Doesn't Exist" After Install](playwright-executable-doesnt-exist.md) cover failure modes that look similar but have different causes.
|
||||
|
||||
## Checking the registry key yourself
|
||||
|
||||
```
|
||||
reg query "HKCU\Software\Mozilla\Firefox\Launcher"
|
||||
```
|
||||
|
||||
Run it before and after a launch at a new path. A new entry appearing is the signal to look for; it won't tell you why the launcher failed the first time, only that the path is now on record.
|
||||
|
||||
## Practical handling: a warm-up launch and one retry
|
||||
|
||||
Two things worked for us. Right after extracting a build to a new path, launch it once and close it immediately, before any real automation depends on it, so the launcher can record the path while nothing is watching the clock.
|
||||
|
||||
```python
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
def launch_with_warmup(playwright, executable_path, **launch_kwargs):
|
||||
# First launch at a brand new path: throwaway, just to let the
|
||||
# launcher record state for this executable. Close it immediately.
|
||||
warmup = playwright.firefox.launch(executable_path=executable_path, **launch_kwargs)
|
||||
warmup.close()
|
||||
return playwright.firefox.launch(executable_path=executable_path, **launch_kwargs)
|
||||
```
|
||||
|
||||
Second, treat the very first real launch of any new install path as worth exactly one retry, no more. The second attempt succeeded every time we tested it, so a loop with backoff solves a problem you don't have and only hides a genuinely broken install behind repeated waiting.
|
||||
|
||||
```python
|
||||
def launch_retry_once(playwright, executable_path, **launch_kwargs):
|
||||
try:
|
||||
return playwright.firefox.launch(executable_path=executable_path, **launch_kwargs)
|
||||
except Exception:
|
||||
return playwright.firefox.launch(executable_path=executable_path, **launch_kwargs)
|
||||
```
|
||||
|
||||
## What remains unexplained
|
||||
|
||||
We have a correlation, not a proven mechanism. We don't know why an absent registry entry makes the launcher exit instead of simply creating the entry itself, the way a first-run step normally would. We also haven't ruled out a competing, more mundane explanation: antivirus or SmartScreen scanning a freshly written executable can delay its first execution at a new path, independent of anything Firefox's own code does.
|
||||
|
||||
Treat the warm-up launch and single retry as a practical workaround, not a fix for a confirmed cause. If what you're chasing turns out to be a preferences problem instead, [Firefox preferences that silently do nothing](firefox-prefs-not-applying.md) covers a different failure that can look similar from the outside.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why does Firefox fail to launch the first time but work the second time?**
|
||||
In our testing, first launches at a brand new path occasionally fail within a fraction of a second, while the second launch at the same path always succeeded. The failure correlates with a Windows registry key that has no entry yet for a path never launched before.
|
||||
|
||||
**Is this a Firefox bug?**
|
||||
We haven't proven that. What we have is a measured correlation between a missing registry entry and an occasional fast failure on first launch, not a confirmed root cause.
|
||||
|
||||
**Does this happen only on Windows?**
|
||||
Yes, as far as we tested. The registry key we found, under `HKCU\Software\Mozilla\Firefox\Launcher`, is Windows-specific, and we have no equivalent finding for Linux.
|
||||
|
||||
**How do I avoid hitting this in automation?**
|
||||
Launch once and close immediately after extracting a build to a new path, before any real task depends on it, and give the first real launch of any new path exactly one retry.
|
||||
|
||||
**Does clearing the cache or profile fix it?**
|
||||
No. Neither made any difference in our testing; the failure tracked the executable's path, not the profile or any cache we cleared.
|
||||
|
||||
**See also:** [Slow browser launch: a per-request timeout is not a budget](slow-browser-launch-timeout-budget.md), [Playwright "Executable Doesn't Exist" After Install](playwright-executable-doesnt-exist.md), and [Firefox preferences that silently do nothing](firefox-prefs-not-applying.md).
|
||||
|
||||
## Sources
|
||||
|
||||
- This project's own testing, September 2026: repeated extraction of a shipped Firefox build to new Windows paths, timing the process exit, and inspecting `HKCU\Software\Mozilla\Firefox\Launcher` before and after each launch.
|
||||
- Mozilla, Gecko Processes, https://firefox-source-docs.mozilla.org/ipc/processes.html - the launcher process on Windows, the quoted line about it launching the parent rather than being launched by it, and its role in DLL blocklisting. Read 5 September 2026.
|
||||
- Mozilla, Launcher Process Failure ping, https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/data/launcher-process-failure-ping.html - the telemetry Firefox sends when the launcher cannot start the browser. Read 5 September 2026; it documents the ping's fields and says nothing about registry state, which is why the registry half above stays labelled as our own observation.
|
||||
|
||||
---
|
||||
|
||||
*From the notes of [invisible_playwright](https://github.com/feder-cr/invisible_playwright), on a failure that only ever showed up once per path and never explained itself in its own words.*
|
||||
@@ -40,6 +40,8 @@ override from the page, because the page is not where the tell originates.
|
||||
- [Execution context was destroyed, and when it means detection](execution-context-destroyed.md) - Usually a race condition, but sometimes a redirect to a challenge; how to tell the two apart.
|
||||
- [Why content_frame() returns None for a cross-origin iframe](cross-origin-iframe-unreachable.md) - One shared cause behind None, throws and timeouts: process isolation, not a permissions bug.
|
||||
|
||||
- [Running Playwright Firefox on ARM64 Linux](playwright-firefox-arm64-linux.md) - What ships per architecture on ARM64 Linux, the emulation trap, and the memory ceiling.
|
||||
|
||||
## Human-like input and interaction
|
||||
|
||||
- [Human-like mouse movement: Bezier curves are the easy part](human-mouse-movement.md) - Every pointer event carries fields saying where it came from, and a perfect curve can still fail.
|
||||
|
||||
@@ -26,6 +26,8 @@ platform the browser claims to be, not just look plausible in isolation.
|
||||
- [WebGL shader precision as a fingerprint surface](webgl-shader-precision-fingerprint.md) - getShaderPrecisionFormat is a third WebGL fingerprint, hashed apart from parameters and extensions.
|
||||
- [Is WebGPU a browser fingerprint?](is-webgpu-a-browser-fingerprint.md) - navigator.gpu exposes a second GPU identity most guides ignore, and it must match WebGL.
|
||||
|
||||
- [Why the same canvas draws differently on Windows and Linux](canvas-differs-across-operating-systems.md) - Why the same canvas call draws different pixels on Windows and on Linux, layer by layer.
|
||||
|
||||
## Fonts, emoji and text metrics
|
||||
|
||||
- [How to make Linux and macOS report real Windows fonts](bundled-fonts-cross-platform.md) - Bundle the real font files and read only from them; filtering a list leaves the host underneath.
|
||||
|
||||
@@ -47,6 +47,8 @@ whether a browser is telling the truth about what it claims to be.
|
||||
- [hCaptcha Enterprise vs Standard](hcaptcha-enterprise-vs-standard.md) - the same mechanism, plus custom difficulty tuning, dedicated risk models and an SLA instead of the free tier's labeled-data economy.
|
||||
- [Cloudflare Bot Management, Explained](cloudflare-bot-management-explained.md) - the always-on scoring engine behind Cloudflare's edge, distinct from the Turnstile widget: a 1-99 bot score from JA3/JA4, HTTP fingerprinting, ML and behavior.
|
||||
|
||||
- [Queue-it virtual waiting rooms, explained for automation](queue-it-virtual-waiting-room-explained.md) - How a virtual waiting room splits the redirect, the return token and the JavaScript half from the server half.
|
||||
|
||||
## What a fingerprint is and how accurate it is
|
||||
|
||||
- [What is a browser fingerprint?](what-is-a-browser-fingerprint.md) - the join of dozens of low-entropy attributes that identify a browser with no cookie.
|
||||
|
||||
@@ -12,10 +12,10 @@ The rest of the Guides explain how a single surface gives you away. This group i
|
||||
other direction: a concrete task, in order, with the code that does it and the specific
|
||||
thing that breaks it.
|
||||
|
||||
Every page here is written against a real browser rather than a generic recipe. The
|
||||
Every page here is written against a real browser instead of a generic recipe. The
|
||||
launch is a two-line change from stock Playwright, the browser returned is a real
|
||||
Playwright `Browser` with no wrapped subset to learn, and each how-to carries at least one
|
||||
mistake we made first, measured and fixed rather than assumed.
|
||||
mistake we made first, measured and fixed, not assumed.
|
||||
|
||||
Start with [how to scrape without getting blocked](how-to-scrape-without-getting-blocked.md)
|
||||
for the model that orders the rest, then pick the task you have.
|
||||
@@ -58,6 +58,8 @@ for the model that orders the rest, then pick the task you have.
|
||||
- [Scrape a map-based search with Playwright](how-to-scrape-map-based-search-playwright.md) - Capture the bounding-box marker XHR, pan and zoom, grid the viewport to cover the area.
|
||||
- [How to scrape map-based local results with Playwright](how-to-scrape-map-based-local-results-playwright.md) - Drive the viewport, capture the bounds-keyed XHR per step, tile an area through an in-region proxy.
|
||||
|
||||
- [Select from dropdowns with Playwright, native and custom](playwright-select-option-dropdowns.md) - select_option() drives a real select element; a custom listbox needs a click, a wait, then a second click.
|
||||
|
||||
## Extracting content and structured data
|
||||
|
||||
- [How to extract JSON-LD structured data with Playwright](how-to-extract-json-ld-structured-data-playwright.md) - Parse JSON-LD and @graph instead of fragile selectors; an empty result reads as a blocked page.
|
||||
@@ -98,13 +100,22 @@ for the model that orders the rest, then pick the task you have.
|
||||
- [How to scrape vacation rental listings with Playwright](how-to-scrape-vacation-rental-listings-playwright.md) - Drive the date and guest inputs, read the fee-inclusive total from the pricing XHR, iterate windows.
|
||||
- [How to scrape hotel room prices with Playwright](how-to-scrape-hotel-prices-playwright.md) - Drive the date and occupancy form, read the rate XHR: rates exist only when you query.
|
||||
- [How to scrape flight prices with Playwright](how-to-scrape-flight-prices-playwright.md) - Wait for the results-complete signal instead of networkidle, then read the settled fare matrix.
|
||||
- [How to scrape flight status boards with Playwright](how-to-scrape-flight-status-boards-playwright.md) - Snapshot a board that rewrites itself in one evaluation, keep scheduled and estimated apart, key rows on the service day.
|
||||
- [How to scrape ferry schedules with Playwright](how-to-scrape-ferry-schedules-playwright.md) - Query date by date because sailings are seasonal, keep direction in the key, record cancellations as events.
|
||||
- [How to scrape flexible-date fare calendars with Playwright](how-to-scrape-fare-calendars-playwright.md) - Wait for each month's price XHR before reading the grid, page forward across a seed-stable sweep.
|
||||
- [How to scrape event and ticket listings with Playwright](how-to-scrape-event-and-ticket-listings-playwright.md) - Wait for the availability XHR, normalise event times to the source timezone, step the calendar.
|
||||
- [How to scrape car listings with Playwright](how-to-scrape-car-listings-playwright.md) - Drive the faceted filter sidebar, wait on the results XHR, pull VIN and specs, then dedupe.
|
||||
- [How to scrape classifieds listings with Playwright](how-to-scrape-classifieds-listings-playwright.md) - Align proxy region and timezone, harvest cards from the rotating feed, drive a contact-reveal click.
|
||||
- [How to scrape business directory listings with Playwright](how-to-scrape-business-directory-listings-playwright.md) - Drive the search form, reveal click-gated phone and email, walk filtered pagination as one visitor.
|
||||
- [How to scrape pet adoption listings with Playwright](how-to-scrape-pet-adoption-listings-playwright.md) - Reconcile each run against the last so a disappearance is data, and key animals on the shelter's own identifier.
|
||||
- [How to scrape job postings with Playwright](how-to-scrape-job-postings-playwright.md) - Drive the faceted search filters, wait for the results XHR, and read the JobPosting JSON-LD.
|
||||
- [How to scrape cryptocurrency prices with Playwright](how-to-scrape-cryptocurrency-prices-playwright.md) - Read WebSocket frames, not the flickering DOM node, and hold the feed open with a stable identity.
|
||||
- [How to scrape EV charging availability with Playwright](how-to-scrape-ev-charging-availability-playwright.md) - Capture the status feed behind the map, keep the operator's timestamp apart from yours, store transitions not snapshots.
|
||||
- [How to scrape fuel prices with Playwright](how-to-scrape-fuel-prices-playwright.md) - Set the location explicitly, keep grade and unit with every price, and record whether the number was reported or observed.
|
||||
- [How to scrape snow reports with Playwright](how-to-scrape-snow-reports-playwright.md) - Pin the unit before reading, keep base and summit as separate measurements, and take the resort's own report time.
|
||||
- [How to scrape parking rates with Playwright](how-to-scrape-parking-rates-playwright.md) - Capture the tariff table as duration bands instead of a price, and keep the small print that outranks the table.
|
||||
- [How to scrape energy tariff comparisons with Playwright](how-to-scrape-energy-tariffs-playwright.md) - Drive the consumption form, keep standing charge and unit rate apart, and copy the inputs into every quoted row.
|
||||
- [How to scrape bank interest rates with Playwright](how-to-scrape-bank-interest-rates-playwright.md) - Resolve the footnote markers while you have the DOM, keep the balance tiers as rows, and take the effective date.
|
||||
- [How to scrape stock and financial data with Playwright](how-to-scrape-stock-and-financial-data-playwright.md) - Scrape fundamentals from tables, capture the live quote stream at the WebSocket or polling XHR.
|
||||
- [How to scrape sports scores and stats with Playwright](how-to-scrape-sports-scores-and-stats-playwright.md) - Read the score feed over a WebSocket, click each stat tab to trigger its XHR, one long session.
|
||||
- [How to scrape forum and community threads with Playwright](how-to-scrape-forum-and-community-threads-playwright.md) - Walk the reply tree depth-first, expand collapsed branches over XHR, strip quoted text.
|
||||
@@ -150,7 +161,11 @@ for the model that orders the rest, then pick the task you have.
|
||||
- [How to scrape breadcrumb hierarchies with Playwright](how-to-scrape-breadcrumb-hierarchies-playwright.md) - read the trail from the markup instead of the truncated text, drop the self crumb, keep the category id from the href, and merge trails o...
|
||||
- [How to scrape fitness class schedules with Playwright](how-to-scrape-class-schedules-playwright.md) - key each row by studio, instructor, room and start time instead of the occurrence id, fetch spots remaining and waitlist state from their...
|
||||
- [How to scrape clinical trial listings with Playwright](how-to-scrape-clinical-trial-listings-playwright.md) - timestamp every status read, carry both trial identifiers, keep eligibility criteria as text, and split target enrollment from site-level...
|
||||
- [How to scrape conference agendas with Playwright](how-to-scrape-conference-agendas-playwright.md) - read the grid as tracks over time so a session keeps its column, resolve the event timezone once, and follow the session pages for speakers.
|
||||
- [How to scrape construction permit records with Playwright](how-to-scrape-construction-permits-playwright.md) - drive the postback search, assert the result count the portal prints, and capture the status history rather than the current stage.
|
||||
- [How to scrape course catalogs with Playwright](how-to-scrape-course-catalogs-playwright.md) - the catalog is a four-level tree, the seat counts live behind a term parameter, and one row per section is the only shape that survives a...
|
||||
- [How to scrape court docket listings with Playwright](how-to-scrape-court-dockets-playwright.md) - work from case numbers you can name rather than enumerating, keep the court's own sequence numbers, and pace it with a written daily cap.
|
||||
- [How to scrape CSS pseudo-element content with Playwright](how-to-scrape-css-pseudo-element-content-playwright.md) - text injected by ::before and ::after is not in the DOM, so read it from getComputedStyle and unwrap the quoted CSS value.
|
||||
- [How to scrape cursor-based pagination with Playwright](how-to-scrape-cursor-pagination-playwright.md) - read endCursor and hasNextPage out of the JSON payload, pass the token back untouched, and checkpoint it with the last item id.
|
||||
- [How to scrape delivery slots with Playwright](how-to-scrape-delivery-slots-playwright.md) - a slot row is keyed to a postcode, a basket and a UTC moment, the grid arrives one week per request, and full is not the same as not offe...
|
||||
- [How to scrape domain WHOIS records with Playwright](how-to-scrape-domain-whois-records-playwright.md) - Scrape WHOIS records with Playwright by parsing labeled fields instead of positions, treating REDACTED FOR PRIVACY as a real value, keepi...
|
||||
@@ -159,13 +174,17 @@ for the model that orders the rest, then pick the task you have.
|
||||
- [How to scrape GraphQL endpoints with Playwright](how-to-scrape-graphql-endpoints-playwright.md) - filter captured calls by the operationName in the POST body, replay persisted queries by hash, check the errors array on a 200, and page ...
|
||||
- [How to scrape infinite carousels with Playwright](how-to-scrape-infinite-carousels-playwright.md) - mark the cloned wrap slides by their own attribute, pause autoplay through reduced motion, track the real slide index, and stop when an i...
|
||||
- [How to scrape insurance quotes with Playwright](how-to-scrape-insurance-quotes-playwright.md) - fill the whole multi-step form fresh per profile, read only the final-step response, and capture every tier a tabbed result renders in on...
|
||||
- [How to scrape library catalog availability with Playwright](how-to-scrape-library-catalog-availability-playwright.md) - read holdings per copy and per branch instead of the record badge, stay inside the session the catalogue issued, and keep its status vocabulary.
|
||||
- [How to scrape live sports scores with Playwright](how-to-scrape-live-sports-scores-playwright.md) - read match state alongside the score, timestamp every update against its own clock, and accept that a score can go down after a VAR review.
|
||||
- [How to scrape currency and locale switchers with Playwright](how-to-scrape-locale-switchers-playwright.md) - find which signal the site obeys by moving one at a time, record the final URL, and separate a display conversion from a real regional pr...
|
||||
- [How to scrape microdata and RDFa markup with Playwright](how-to-scrape-microdata-markup-playwright.md) - walk [itemscope] and [itemprop] with page.evaluate, apply the nine-case value rule instead of textContent, resolve itemref, and read RDFa...
|
||||
- [How to scrape multi-select facet filters with Playwright](how-to-scrape-multi-select-facets-playwright.md) - expand show-more first, wait for the facet response before reading counts, store the state URL on every row, and sweep one group at a time.
|
||||
- [How to scrape newsletter archives with Playwright](how-to-scrape-newsletter-archives-playwright.md) - page until the archive repeats or runs dry, read the hosted rendering instead of the sent email, and resolve tracking-redirect links once...
|
||||
- [How to scrape numbers rendered as images with Playwright](how-to-scrape-numbers-rendered-as-images-playwright.md) - look in the accessible layer and the sprite offsets before reaching for pixels, and compare decoded pixels rather than PNG bytes.
|
||||
- [How to scrape nutrition labels with Playwright](how-to-scrape-nutrition-labels-playwright.md) - map every column to its per 100 g, per serving or per package basis, split the serving size, keep kilojoules and kilocalories apart, and ...
|
||||
- [How to scrape open data portals with Playwright](how-to-scrape-open-data-portals-playwright.md) - name the catalogue product from its JSON response shape, page its documented listing API, and open a browser only where the search UI hid...
|
||||
- [How to scrape package download statistics with Playwright](how-to-scrape-package-download-stats-playwright.md) - take the series the chart draws from, keep the version breakdown, and carry the mirror and CI caveats next to the number.
|
||||
- [How to scrape package tracking status with Playwright](how-to-scrape-package-tracking-playwright.md) - capture the event timeline rather than the headline status, merge revisions instead of appending, and widen the poll when nothing moves.
|
||||
- [How to scrape patent listings with Playwright](how-to-scrape-patent-listings-playwright.md) - bind each date to its labeled field, keep family members and claim dependencies intact instead of flattening them, and stamp legal status...
|
||||
- [How to scrape podcast episode listings with Playwright](how-to-scrape-podcast-episodes-playwright.md) - find the RSS feed behind the player, key episodes on the guid, and parse durations and episode numbers that arrive in several shapes.
|
||||
- [How to scrape podcast transcripts with Playwright](how-to-scrape-podcast-transcripts-playwright.md) - fetch the underlying VTT or SRT file instead of scrolling the panel, keep cue timing and text as rows, and detect speaker labels and auto...
|
||||
@@ -174,12 +193,15 @@ for the model that orders the rest, then pick the task you have.
|
||||
- [How to scrape range slider filters with Playwright](how-to-scrape-range-slider-filters-playwright.md) - read aria-valuenow instead of calling fill, prefer the URL parameter, wait for the debounced response, and sweep the field in half-open b...
|
||||
- [How to scrape recipe data with Playwright](how-to-scrape-recipe-data-playwright.md) - read the JSON-LD Recipe node, flatten the three recipeInstructions shapes, split ingredient strings, and parse ISO 8601 times.
|
||||
- [How to scrape salary and pay scale data with Playwright](how-to-scrape-salary-data-playwright.md) - expand the hidden pay breakdown, keep the range and period intact, tag self-reported figures apart from wage statistics, and carry sample...
|
||||
- [How to scrape scholarship listings with Playwright](how-to-scrape-scholarship-listings-playwright.md) - parse the deadline into a shape that admits it is often not a date, keep eligibility as prose, and follow through to the provider page.
|
||||
- [How to scrape school term calendars with Playwright](how-to-scrape-school-term-calendars-playwright.md) - prefer the calendar feed the page links to, expand ranges with an inclusive end, and keep a closure distinct from a staff day.
|
||||
- [How to scrape flight seat maps with Playwright](how-to-scrape-seat-maps-playwright.md) - Scrape flight seat maps with Playwright by reading each seat's own data attribute instead of its position, joining status and pricing fro...
|
||||
- [How to scrape server-sent events with Playwright](how-to-scrape-server-sent-events-playwright.md) - the response event fires but body() never returns, so replace window.EventSource in an init script, wrap fetch, and parse text/event-stre...
|
||||
- [How to scrape shipping rates with Playwright](how-to-scrape-shipping-rates-playwright.md) - a rate is keyed to destination, weight, dimensions and service level, the quote response carries surcharge lines the total hides, and fre...
|
||||
- [How to scrape size charts with Playwright](how-to-scrape-size-charts-playwright.md) - open the modal that holds the table, record which unit the toggle had active, detect row-versus-column orientation, and mark image-only c...
|
||||
- [How to scrape software changelogs and release notes with Playwright](how-to-scrape-software-changelogs-playwright.md) - detect the page shape, parse versions into sortable tuples, read the change type from the heading above each bullet, and stop at the vers...
|
||||
- [How to scrape sortable data tables with Playwright](how-to-scrape-sortable-tables-playwright.md) - read rows once keyed on an identifier, trust aria-sort over a click count, and sort the data yourself instead of the page's own string co...
|
||||
- [How to scrape spare part compatibility with Playwright](how-to-scrape-spare-part-compatibility-playwright.md) - drive the cascading dropdowns waiting on each level to repopulate, key results on the whole path, and keep the fitment notes.
|
||||
- [How to scrape stock levels with Playwright](how-to-scrape-stock-levels-playwright.md) - the badge is a bucket, the number lives in the variant endpoint, and a reading without a timestamp and a variant id is not a stock level.
|
||||
- [How to scrape store locator pages with Playwright](how-to-scrape-store-locator-pages-playwright.md) - seed the search with a point grid instead of postcodes, read the radius endpoint rather than the cards, and dedupe on the store id becaus...
|
||||
- [How to scrape public tender notices with Playwright](how-to-scrape-tender-notices-playwright.md) - one row per lot, deadlines kept with the offset the response carries, classification-code filters, and a re-scrape that reconciles revisi...
|
||||
|
||||
@@ -50,7 +50,11 @@ telling the difference before you ship a fix, not after.
|
||||
- [Playwright TargetClosedError: the causes and the fixes](playwright-targetclosederror-causes.md) - usually not a timeout; three specific Firefox and Juggler causes, their symptoms, and how to tell them apart.
|
||||
- [Firefox preferences that silently do nothing](firefox-prefs-not-applying.md) - a preference you set can be silently ignored with no error; the reasons in order, and how to confirm which one you hit.
|
||||
|
||||
- [First Firefox launch fails on Windows, then works](first-firefox-launch-fails-then-works-windows.md) - The first launch of a freshly extracted build fails, every later one works: what Windows remembers between the two.
|
||||
- [Keep Playwright Firefox memory flat on long runs](playwright-firefox-memory-long-runs.md) - Memory that grows over a long run comes from unclosed contexts, an accumulating list, or one context kept too long.
|
||||
|
||||
## Canvas, screenshots and fingerprint noise
|
||||
|
||||
- [Canvas fingerprint changes every run: use a seed](canvas-fingerprint-changes-every-run.md) - canvas, WebGL and audio hashes change each run; pass a fixed seed to make readbacks byte-identical.
|
||||
- [Playwright screenshot returns noise: readback fix](playwright-screenshot-returns-noise.md) - why page.screenshot() returned a noise PNG, and the principal-split canvas readback fix that made captures clean.
|
||||
- [Missing fonts in Docker break Playwright screenshots](playwright-firefox-fonts-docker.md) - A container ships almost no fonts, so text renders as boxes or as the wrong family.
|
||||
@@ -19,7 +19,7 @@ underneath, the same mechanism.
|
||||
The short version: Enterprise is not a stricter widget. It is the same
|
||||
checkbox-or-invisible, escalate-to-a-puzzle model, given a visible risk score, custom
|
||||
challenge content, difficulty controls a free integration never sees, and a support
|
||||
contract, sold as a metered or negotiated product rather than embedded for free in
|
||||
contract, sold as a metered or negotiated product, not embedded for free in
|
||||
exchange for the puzzle answers themselves.
|
||||
|
||||
## Three tiers, not two
|
||||
@@ -31,7 +31,7 @@ choosing among four fixed difficulty modes: "Easy, Medium, Difficult, and Auto."
|
||||
is a paid, self-serve tier priced, per hCaptcha's own pricing page, at "$99/month"
|
||||
billed annually or "$139/month" billed monthly, including 100,000 evaluations a month
|
||||
with overage at "$0.99/1K" beyond that, with a two-week free trial. **Enterprise** is
|
||||
custom-priced and sold through a sales contact rather than a checkout page.
|
||||
custom-priced and sold through a sales contact, not a checkout page.
|
||||
|
||||
## What Pro adds over Basic
|
||||
|
||||
@@ -49,10 +49,10 @@ score, or the analytics.
|
||||
|
||||
## What Enterprise adds on top of Pro
|
||||
|
||||
This is the part that is a genuine capability gap rather than a bigger number on the
|
||||
This is the part that is a genuine capability gap instead of a bigger number on the
|
||||
same feature, and hCaptcha's own plans page names it directly: **private learning**,
|
||||
described as training detection models on an Enterprise customer's own traffic patterns
|
||||
rather than a shared, general model, plus **custom challenges** and **challenge content
|
||||
in place of a shared, general model, plus **custom challenges** and **challenge content
|
||||
control**, meaning an Enterprise account can bring its own images or questions instead
|
||||
of using hCaptcha's default challenge pool. hCaptcha's plans page also lists **human
|
||||
threat detection**, **difficulty tuning**, called out specifically as including the
|
||||
@@ -71,7 +71,7 @@ gives that customer direct control over what the puzzle even looks like, and add
|
||||
operational scaffolding (SLA, SSO, reporting) an organization actually deploying this at
|
||||
scale asks for. None of it is a stricter version of the puzzle itself, it is control
|
||||
over when and how the puzzle appears, and how well the risk model fits one customer's
|
||||
own traffic rather than the general population hCaptcha sees.
|
||||
own traffic instead of the general population hCaptcha sees.
|
||||
|
||||
| | Basic (free) | Pro | Enterprise |
|
||||
|---|---|---|---|
|
||||
|
||||
@@ -19,7 +19,7 @@ validating itself against the one call almost no real script makes.
|
||||
Every guide to human-like mouse movement measures the same thing: draw a curve, add
|
||||
jitter, check that the shape looks plausible. [The curve is the easy half](human-mouse-movement.md).
|
||||
This page is about a failure mode one level up, found by measuring the feature on the
|
||||
call scripts actually make rather than the one it's easiest to test with, and it
|
||||
call scripts actually make instead of the one it's easiest to test with, and it
|
||||
turned out the humanization had been validating itself against the wrong call the
|
||||
whole time.
|
||||
|
||||
@@ -45,7 +45,7 @@ That is a teleport with two extra samples decorating it, not a human path.
|
||||
|
||||
## Why the hit-target check eats the movement
|
||||
|
||||
The mechanism is specific rather than mysterious. A hit-target check has to move the
|
||||
The mechanism is specific, not mysterious. A hit-target check has to move the
|
||||
pointer onto the target before it can confirm the target is really there. If the
|
||||
humanized path is generated *inside* that same step, the check consumes the distance
|
||||
first, and the path that runs afterward has almost nothing left to cover. The stroke
|
||||
|
||||
@@ -16,7 +16,7 @@ and its neighbours is real, it is worth doing, and it is also the cheapest thing
|
||||
detector checks. The durable tells are not values you can redefine from a page
|
||||
script. They are outputs a real machine produces and a script cannot: what the
|
||||
engine actually renders, what it can actually decrypt, how a pointer actually moves.
|
||||
Building toward that from the start, rather than patching properties after a block
|
||||
Building toward that from the start, not patching properties after a block
|
||||
shows up, is the difference this page is about.
|
||||
|
||||
This page is written for before you launch a session, not after one gets blocked. If
|
||||
@@ -43,14 +43,14 @@ ceiling:
|
||||
|
||||
[The full breakdown of what each level can and cannot reach is
|
||||
here](playwright-stealth-levels.md). The proactive move is to pick a level
|
||||
deliberately, before you write a line of scraping code, rather than discovering the
|
||||
deliberately, before you write a line of scraping code, not discovering the
|
||||
ceiling of level 1 three weeks into a project when a site starts checking something
|
||||
a page script cannot touch.
|
||||
|
||||
## Start from what a level-1 patch actually buys you
|
||||
|
||||
`navigator.webdriver` is the property everyone reaches for first, and it is worth
|
||||
doing correctly rather than skipping. The naive version looks like this:
|
||||
doing correctly instead of skipping. The naive version looks like this:
|
||||
|
||||
```python
|
||||
from playwright.sync_api import sync_playwright
|
||||
@@ -90,13 +90,13 @@ none of them are JavaScript properties:
|
||||
- **The behaviour.** How the pointer moves, how a form gets filled, whether the page
|
||||
is ever scrolled.
|
||||
|
||||
This is the argument for moving down a level rather than writing a longer init
|
||||
This is the argument for moving down a level instead of writing a longer init
|
||||
script. A property can be redefined by anyone with a console. An output has to be
|
||||
produced by something that actually has the capability being tested.
|
||||
|
||||
## The capability check a Playwright property patch cannot pass
|
||||
|
||||
A capability check asks the browser to do something rather than report something,
|
||||
A capability check asks the browser to do something, not report something,
|
||||
which is why a page-level patch cannot pass one. Here is a concrete version you can
|
||||
run yourself against whatever Playwright launches today.
|
||||
|
||||
@@ -124,7 +124,7 @@ with sync_playwright() as p:
|
||||
|
||||
On a default managed Chromium this prints `no`. Setting the user agent to claim
|
||||
Chrome does not change the answer, because the missing piece is a DRM module, not a
|
||||
string. [The full argument, including why this is a capability rather than a
|
||||
string. [The full argument, including why this is a capability, not a
|
||||
value and what closes it, is here](chromium-is-not-chrome.md). No `add_init_script`
|
||||
reaches this, because there is no property to redefine. The module either exists in
|
||||
the binary or it does not.
|
||||
|
||||
@@ -95,7 +95,7 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
```
|
||||
|
||||
Two habits worth keeping. Build the destination name from
|
||||
`suggested_filename` rather than from link text, and always assert a non-zero
|
||||
`suggested_filename`, not from link text, and always assert a non-zero
|
||||
size afterwards. An empty file that saved without raising is the download
|
||||
equivalent of a page that came back blank: it did not error, and it is still a
|
||||
failure.
|
||||
|
||||
@@ -51,7 +51,7 @@ that happens to be all furniture and no article.
|
||||
## Render first: wait for the body, then take page.content()
|
||||
|
||||
The fix has two halves. Let the page finish rendering, then hand the *rendered*
|
||||
HTML to the extractor rather than the initial response.
|
||||
HTML to the extractor instead of the initial response.
|
||||
|
||||
[`page.content()`](https://playwright.dev/python/docs/api/class-page#page-content)
|
||||
serialises the live DOM as it stands now, after scripts have run and injected
|
||||
@@ -146,7 +146,7 @@ reading it *after* the body was injected.
|
||||
|
||||
## Why a real engine sees paragraphs an HTTP fetch never receives
|
||||
|
||||
There is a reason this recipe uses a browser at all rather than `requests` plus
|
||||
There is a reason this recipe uses a browser at all, not `requests` plus
|
||||
readability. The clean-extraction problem and the not-getting-blocked problem
|
||||
share a root cause, and it is worth being explicit about.
|
||||
|
||||
@@ -168,7 +168,7 @@ wearing two hats.
|
||||
This is where a consistent, real-looking fingerprint earns its place. Because
|
||||
`InvisiblePlaywright` derives every surface - GPU, canvas, audio, fonts, screen
|
||||
- from one seed, `seed=42` gets you the same coherent machine on every run, so
|
||||
the same full article is served each time rather than the article once and a
|
||||
the same full article is served each time instead of the article once and a
|
||||
stripped variant the next. That reproducibility is also what makes a broken
|
||||
extraction debuggable: a failing run replays exactly instead of vanishing into
|
||||
the next random draw. The general version of "get the real page, not the bot
|
||||
@@ -187,7 +187,7 @@ Three cheap checks catch most of the failures:
|
||||
|
||||
- **Byline and headline survived.** These often sit in their own elements
|
||||
outside the main content block, and readability drops them more often than it
|
||||
drops paragraphs. If you need the author, extract it separately rather than
|
||||
drops paragraphs. If you need the author, extract it separately instead of
|
||||
hoping the summary kept it.
|
||||
- **It did not truncate at an inline widget.** A pull-quote, an embedded video,
|
||||
a subscribe box or a mid-article "related" card can look like the end of the
|
||||
|
||||
@@ -14,7 +14,7 @@ To extract JSON-LD structured data with Playwright, select every
|
||||
`all_text_contents()`, and `json.loads` it; then flatten any `@graph` array and filter
|
||||
by `@type` instead of trusting document order. It is less fragile than chasing CSS
|
||||
selectors, and an empty result is a useful signal that you were handed a blocked or
|
||||
simplified page rather than the real one.
|
||||
simplified page instead of the real one.
|
||||
|
||||
Most scraping guides teach you to chase CSS selectors down through a layout that
|
||||
changes the week after you ship. There is often a cleaner record sitting on the same
|
||||
@@ -48,7 +48,7 @@ The difference in practice:
|
||||
A class name changes, a wrapper `div` moves, a component re-renders with different
|
||||
attributes, and your selector-based extractor breaks. The JSON-LD block is a contract
|
||||
with search engines, so it changes far less often and, when it does, it changes in a
|
||||
documented shape rather than an arbitrary one.
|
||||
documented shape, not an arbitrary one.
|
||||
|
||||
The one thing to know before you start: a page can carry several blocks of different
|
||||
`@type`, and they can be nested inside a `@graph` array. You cannot take the first
|
||||
@@ -90,10 +90,10 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
```
|
||||
|
||||
`all_text_contents()` returns the text of every matching `<script>` tag, so you get
|
||||
all of them in one call rather than looping locators by hand. `json.loads` turns each
|
||||
all of them in one call instead of looping locators by hand. `json.loads` turns each
|
||||
into a Python object. The `seed=42` gives you a reproducible identity so that if one
|
||||
run gets the block and another does not, you can replay the exact same browser and
|
||||
find out why rather than blaming the random draw.
|
||||
find out why instead of blaming the random draw.
|
||||
|
||||
## Filter by @type, and walk the @graph
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ links, a tenth of the pages return an empty dict, and a few come back looking pe
|
||||
from a page that never actually loaded for you.
|
||||
|
||||
This page is the four things that turn that one-liner into something you can trust:
|
||||
where the tags really live, why you must read the rendered head rather than the first
|
||||
where the tags really live, why you must read the rendered head instead of the first
|
||||
response, how to resolve a relative `og:image`, and the fallback chain to use when a
|
||||
key is simply absent. It ends on one honest caveat that is specific to running against
|
||||
sites that would rather you did not.
|
||||
|
||||
@@ -63,7 +63,7 @@ The engine's mouse model handles per-action realism, not request cadence, so it
|
||||
rate limit your loop for you. It is worth being precise about what the engine already does,
|
||||
because it covers one behaviour signal and not the other.
|
||||
|
||||
Every click arcs the pointer to the target along a Bezier curve rather than teleporting to
|
||||
Every click arcs the pointer to the target along a Bezier curve instead of teleporting to
|
||||
the coordinate, which adds a realistic, variable latency to each action and is
|
||||
[movement that is produced rather than declared](human-mouse-movement.md). That defeats
|
||||
the pointer-teleport tell inside a page.
|
||||
|
||||
@@ -68,7 +68,7 @@ That matters for reading a benchmark because a table that lists five tools as fi
|
||||
independent data points, when three of them share a code ancestor or the same underlying
|
||||
CDP quirks, is reporting less independent evidence than it looks like it's reporting.
|
||||
Three rows agreeing is weaker evidence than it appears if the three rows are close
|
||||
cousins rather than three separate engineering efforts arriving at the same answer.
|
||||
cousins, not three separate engineering efforts arriving at the same answer.
|
||||
|
||||
## What a trustworthy report actually looks like, with a real example
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ nav_order: 74
|
||||
|
||||
To resume an interrupted Playwright scrape, write a small durable checkpoint after each
|
||||
unit of work, then on restart skip the work already done, re-validate the boundary item,
|
||||
and relaunch with the same seed so the site sees one returning visitor rather than a new
|
||||
and relaunch with the same seed so the site sees one returning visitor instead of a new
|
||||
one. Stock Playwright gives you the checkpoint and the resume path; a seeded fingerprint
|
||||
keeps the resumed run continuous.
|
||||
|
||||
@@ -26,7 +26,7 @@ There is a second failure most guides miss. If every restart launches a fresh br
|
||||
identity, the site does not see one job that hiccuped. It sees a new visitor appear each
|
||||
time the job restarts, which is a pattern in its own right. The fix for that is the same
|
||||
lever this project uses everywhere: a seeded, reproducible fingerprint, so a resumed run
|
||||
is the same visitor coming back rather than a new one arriving.
|
||||
is the same visitor coming back, not a new one arriving.
|
||||
|
||||
## Why a naive restart is the worst of both options
|
||||
|
||||
@@ -53,7 +53,7 @@ a paginated crawl it is the last page number and the last item ID on it. For a c
|
||||
it is the cursor token the server handed you. For a list of URLs it is the set of URLs
|
||||
already done.
|
||||
|
||||
Two rules make it durable rather than decorative. Write it incrementally, after each unit
|
||||
Two rules make it durable, not decorative. Write it incrementally, after each unit
|
||||
of work, not once at the end where a crash guarantees you never reach it. And write it
|
||||
atomically, so a crash in the middle of writing the file cannot leave you with a
|
||||
half-written checkpoint that is worse than none.
|
||||
@@ -142,7 +142,7 @@ def run():
|
||||
|
||||
`done_ids` doing the dedup means the boundary page can be re-read safely: rows already
|
||||
written are skipped by ID, so re-validating costs you a re-fetch and never a duplicate. For
|
||||
larger runs, keep `done_ids` in a set-backed store (a SQLite table, a Redis set) rather than
|
||||
larger runs, keep `done_ids` in a set-backed store (a SQLite table, a Redis set) in place of
|
||||
a growing JSON array, but the shape is identical.
|
||||
|
||||
If a page fails transiently rather than fatally, resuming the whole process is the wrong
|
||||
|
||||
@@ -29,7 +29,7 @@ mention it because their browser cannot fix it anyway.
|
||||
|
||||
Rotate the proxy once per browser session, not once per request: give one browser
|
||||
launch one proxy and hold it for the whole visit, then close the session and start the
|
||||
next one on a different proxy. This is the [sticky-session pattern rather than a
|
||||
next one on a different proxy. This is the [sticky-session pattern instead of a
|
||||
per-request rotating pool](sticky-vs-rotating-proxy-sessions.md), and for a browser it
|
||||
is the correct default.
|
||||
|
||||
@@ -68,7 +68,7 @@ for i, proxy in enumerate(proxies):
|
||||
|
||||
Each iteration is a separate process, a separate seed, and a separate proxy. Each one
|
||||
gets its own canvas hash, GPU string, font set and timezone, because those are derived
|
||||
from the seed and the exit rather than left over from the previous session. That is
|
||||
from the seed and the exit, not left over from the previous session. That is
|
||||
also the property a shared-browser, proxy-per-context setup does not have: every
|
||||
context in one browser reports the same hardware regardless of which proxy it is
|
||||
tunneled through, which is exactly what
|
||||
@@ -114,7 +114,7 @@ with InvisiblePlaywright(proxy=proxy) as browser:
|
||||
```
|
||||
|
||||
A `socks5://` or `socks4://` server is written into the browser's own proxy
|
||||
preferences, credentials included, rather than handed to Playwright's proxy layer
|
||||
preferences, credentials included, not handed to Playwright's proxy layer
|
||||
where the credentials are silently dropped. `http://` and `https://` servers go to
|
||||
Playwright directly, because that is the path where its credential support is real.
|
||||
The endpoint needs an explicit port; a bare host with no port is refused rather than
|
||||
|
||||
@@ -9,7 +9,7 @@ nav_order: 63
|
||||
|
||||
# How to scrape a sitemap.xml with Playwright
|
||||
|
||||
To scrape a `sitemap.xml` with Playwright, treat it as a tree rather than a flat list: read
|
||||
To scrape a `sitemap.xml` with Playwright, treat it as a tree instead of a flat list: read
|
||||
the root element to tell a `<sitemapindex>` from a `<urlset>`, recurse into the child
|
||||
sitemaps, decompress any `.xml.gz` leaves, and key each URL on its `<lastmod>` so later runs
|
||||
recrawl only what changed. Fetch the whole tree through the browser context, because the file
|
||||
@@ -56,7 +56,7 @@ A **sitemap index** is a table of contents whose `<loc>` values point at more si
|
||||
|
||||
The single most common way this code breaks is iterating a document as if it were a url set
|
||||
when it is really an index. You get a list of `<loc>` values that look like URLs, you crawl
|
||||
them, and every one is another XML file rather than a page. So the rule is: read the root
|
||||
them, and every one is another XML file, not a page. So the rule is: read the root
|
||||
element first and branch on it. Never assume the shape.
|
||||
|
||||
Child sitemaps are frequently gzip-compressed and served as `.xml.gz`, because an
|
||||
@@ -75,7 +75,7 @@ driving, it returns the file.
|
||||
So fetch it through the browser context.
|
||||
[Playwright's request API](https://playwright.dev/python/docs/api/class-apirequestcontext) sends
|
||||
the fetch through the same browser network stack, sharing its cookies, its proxy, and its
|
||||
engine-level handshake, which is the whole point of using a patched engine rather than a
|
||||
engine-level handshake, which is the whole point of using a patched engine instead of a
|
||||
header generator. With `invisible_playwright` that browser is a real Firefox patched at the
|
||||
C++ level and driven by stock Playwright, so switching to it is the launch line and nothing else:
|
||||
|
||||
@@ -99,7 +99,7 @@ def fetch_xml(page, url):
|
||||
return ET.fromstring(raw)
|
||||
```
|
||||
|
||||
`resp.body()` gives you the raw bytes rather than a decoded string, which matters because a
|
||||
`resp.body()` gives you the raw bytes in place of a decoded string, which matters because a
|
||||
`.xml.gz` leaf is not text yet. Checking the
|
||||
[two-byte gzip magic](https://datatracker.ietf.org/doc/html/rfc1952) and calling
|
||||
`gzip.decompress` handles the compressed case; a file the server already decompressed for you
|
||||
|
||||
@@ -92,7 +92,7 @@ raises nothing, because an empty string is a legal value for an empty element. A
|
||||
forty panels finishes green, writes forty rows, and every row is blank.
|
||||
|
||||
That is why the guard above is not decoration. An empty panel means your assumption about
|
||||
the page was wrong, and the run should stop and say so rather than fill a file with nothing.
|
||||
the page was wrong, and the run should stop and say so, not fill a file with nothing.
|
||||
|
||||
## aria-expanded and aria-controls beat class names
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ nav_order: 100
|
||||
To scrape appointment availability with Playwright, capture the calendar response the
|
||||
page fetches for each week or month instead of reading the painted cells, key every row
|
||||
to the provider, the service type and the location it was resolved for, stamp it in UTC
|
||||
when the response lands, and stop at the grid rather than clicking a slot, because in
|
||||
when the response lands, and stop at the grid instead of clicking a slot, because in
|
||||
many systems selecting one places a hold that takes it away from every other visitor.
|
||||
|
||||
An appointment grid looks like a published schedule and behaves like contested
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
---
|
||||
title: "How to scrape bank interest rates with Playwright"
|
||||
description: "Scrape published deposit and lending rates with Playwright: resolve the footnotes that change the rate, keep the balance tiers separate, and record the effective date the bank prints."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 164
|
||||
---
|
||||
|
||||
|
||||
# How to scrape bank interest rates with Playwright
|
||||
|
||||
To scrape published rates, capture the **footnote with the number**. A rate table on a
|
||||
bank site is a set of headline figures whose real meaning lives in the small print
|
||||
underneath: an introductory period, a balance tier, a requirement to hold another product,
|
||||
a rate that drops after twelve months. The headline without its footnote is not a
|
||||
simplification, it is a different number.
|
||||
|
||||
The second structural fact is tiering. One product usually has several rates, one per
|
||||
balance band, and the page shows the best one in large type. A scrape that takes the large
|
||||
type produces a table where every bank looks like its best case.
|
||||
|
||||
This page covers resolving footnote markers to their text, reading tiers as rows, and
|
||||
keeping the effective date the bank publishes.
|
||||
|
||||
## Resolve the marker to the text, at capture time
|
||||
|
||||
Footnote markers are superscripts that point at a list further down the page. Follow the
|
||||
pointer while you have the DOM:
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
RESOLVE = """
|
||||
() => {
|
||||
const notes = {};
|
||||
document.querySelectorAll('.footnotes li[id]').forEach(li => {
|
||||
notes[li.id] = li.textContent.trim();
|
||||
});
|
||||
return Array.from(document.querySelectorAll('table.rates tbody tr')).map(tr => {
|
||||
const cells = Array.from(tr.querySelectorAll('td')).map(td => td.textContent.trim());
|
||||
const marks = Array.from(tr.querySelectorAll('sup a[href^="#"]'))
|
||||
.map(a => notes[a.getAttribute('href').slice(1)])
|
||||
.filter(Boolean);
|
||||
return { cells, footnotes: marks };
|
||||
});
|
||||
}
|
||||
"""
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example-bank.com/savings/rates")
|
||||
page.wait_for_selector("table.rates tbody tr")
|
||||
rows = page.evaluate(RESOLVE)
|
||||
```
|
||||
|
||||
Doing this in one evaluation matters because the markers and the notes are in different
|
||||
parts of the document, and resolving them later from two separately captured lists means
|
||||
matching on an id you may not have kept.
|
||||
|
||||
## Tiers are rows, and the tier bounds are part of the rate
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
TIER = re.compile(r"(?P<lo>[\d,]+)\s*(?:to|-|and above|\+)?\s*(?P<hi>[\d,]+)?", re.I)
|
||||
|
||||
def parse_tier(text):
|
||||
m = TIER.search(text.replace("$", "").replace("£", ""))
|
||||
if not m:
|
||||
return {"tier_text": text}
|
||||
return {
|
||||
"tier_text": text,
|
||||
"min_balance": int(m.group("lo").replace(",", "")),
|
||||
"max_balance": int(m.group("hi").replace(",", "")) if m.group("hi") else None,
|
||||
}
|
||||
```
|
||||
|
||||
A null `max_balance` means the top band, which is open ended. Keep `tier_text` as well,
|
||||
because banks write bands in ways this regex will not always survive, and the original
|
||||
string is what lets you tell a parse failure from an unusual product.
|
||||
|
||||
## APR and APY are not interchangeable
|
||||
|
||||
Deposit products publish an annual yield that includes compounding; lending products
|
||||
publish an annual rate that includes fees, under names that vary by country. The two are
|
||||
not comparable and the page often shows both:
|
||||
|
||||
```python
|
||||
row["rate_kind"] = header_for(column_index) # "APY", "APR", "AER", "nominal"
|
||||
```
|
||||
|
||||
Take the label from the column header instead of assuming. Storing every percentage in a
|
||||
column called `rate` merges two different quantities, and the error is invisible until
|
||||
someone compares a savings account to a loan and gets a sensible-looking answer.
|
||||
|
||||
## Effective date, and the fact that these pages are cached hard
|
||||
|
||||
Banks print an effective date, and it is the closest thing to a timestamp the data has:
|
||||
|
||||
```python
|
||||
node = page.query_selector(".rates-effective, .as-of-date")
|
||||
row["effective_text"] = node.inner_text().strip() if node else None
|
||||
row["captured_at"] = time.time()
|
||||
```
|
||||
|
||||
Keep both, for the same reason as any live-status scrape: the page you fetched today may
|
||||
be serving a rate table from last week, and the effective date is the only field that
|
||||
reveals it. If the effective date has not moved in weeks while a central bank has, the
|
||||
page is stale, not the rates being unchanged.
|
||||
|
||||
## Products live behind a selector
|
||||
|
||||
Larger banks put rates behind a product picker, a region picker, or both, with no URL
|
||||
change. Set them explicitly and record them:
|
||||
|
||||
```python
|
||||
page.select_option("select#region", "CA")
|
||||
page.select_option("select#product", "TFSA")
|
||||
page.wait_for_selector("table.rates tbody tr")
|
||||
row["region"] = "CA"
|
||||
row["product"] = "TFSA"
|
||||
```
|
||||
|
||||
Rates genuinely differ by region within the same bank, and a table captured without the
|
||||
region column cannot be compared with itself next month. Where the region is inferred from
|
||||
the visitor rather than selected, that is
|
||||
[geotargeted content](how-to-scrape-geotargeted-content-playwright.md) and the exit
|
||||
becomes part of the query.
|
||||
|
||||
## Read the published rate, and nothing behind a login
|
||||
|
||||
Everything above is the public rate card, which banks publish deliberately and update on a
|
||||
schedule. The parts behind authentication are account data belonging to a person, and the
|
||||
reasoning in
|
||||
[why automating login is riskier than reusing a session](automating-login-vs-session-reuse.md)
|
||||
applies with the extra weight that financial institutions treat automated access to
|
||||
accounts as a security event, correctly.
|
||||
|
||||
Public rate cards change daily at most, usually less. A daily pass is generous, the pacing
|
||||
in [rate limiting your own scraper](how-to-rate-limit-your-scraper-playwright.md) applies,
|
||||
and storing the history in
|
||||
[a SQLite database](how-to-scrape-into-a-database-playwright.md) gives you the one thing
|
||||
the bank's own page never shows: what the rate used to be.
|
||||
|
||||
## A complete pass over several products
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
PRODUCTS = [("CA", "TFSA"), ("CA", "GIC"), ("CA", "SAVINGS")]
|
||||
|
||||
def read_rates(page, region, product):
|
||||
page.goto("https://example-bank.com/savings/rates", wait_until="domcontentloaded")
|
||||
page.select_option("select#region", region)
|
||||
page.select_option("select#product", product)
|
||||
page.wait_for_function(
|
||||
"() => document.querySelectorAll('table.rates tbody tr').length > 0")
|
||||
|
||||
node = page.query_selector(".rates-effective, .as-of-date")
|
||||
effective = node.inner_text().strip() if node else None
|
||||
kinds = page.eval_on_selector_all(
|
||||
"table.rates thead th", "els => els.map(e => e.textContent.trim())")
|
||||
|
||||
rows = []
|
||||
for parsed in page.evaluate(RESOLVE):
|
||||
cells, notes = parsed["cells"], parsed["footnotes"]
|
||||
if len(cells) < 2:
|
||||
continue
|
||||
rows.append({
|
||||
"region": region, "product": product,
|
||||
**parse_tier(cells[0]),
|
||||
"rate_text": cells[1],
|
||||
"rate_kind": kinds[1] if len(kinds) > 1 else None,
|
||||
"footnotes": notes,
|
||||
"effective_text": effective,
|
||||
"observed_at": time.time(),
|
||||
})
|
||||
return rows
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("rates.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
for region, product in PRODUCTS:
|
||||
for row in read_rates(page, region, product):
|
||||
out.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(4000)
|
||||
```
|
||||
|
||||
Reading the column headers into `rate_kind` rather than hardcoding "APY" is what keeps the
|
||||
dataset correct when the bank reorders its table or serves a different label by region.
|
||||
It costs one line and removes a whole class of silent mismatch.
|
||||
|
||||
## Banks cache hard, and that is the failure to design for
|
||||
|
||||
Retail banking sites are rarely hostile to a reader, and they are aggressively cached and
|
||||
heavily regionalised. Three consequences.
|
||||
|
||||
**A stale page is the normal failure.** The request succeeds, the table renders, and the
|
||||
effective date is from last week. That is why `effective_text` is captured on every row
|
||||
rather than derived once: without it, a series shows a rate holding steady when the page
|
||||
simply was not refreshed.
|
||||
|
||||
**The region control sometimes loses.** Where the site also infers a region from the
|
||||
visitor, selecting one in the dropdown can be overridden on the next navigation. Read the
|
||||
region back from the page after the table loads, and record what the page says rather than
|
||||
what you asked for:
|
||||
|
||||
```python
|
||||
shown = page.eval_on_selector("select#region", "e => e.value")
|
||||
if shown != region:
|
||||
row["region_requested"], row["region"] = region, shown
|
||||
```
|
||||
|
||||
**Product pages sit behind an interstitial.** Regulatory splash screens and region pickers
|
||||
appear on first visit in several markets, and a run that does not clear them reads the
|
||||
splash instead of the rates. Handle it once per session the same way as any
|
||||
[cookie consent banner](how-to-handle-cookie-consent-banners-playwright.md).
|
||||
|
||||
If a rate table does come back empty rather than stale, the page itself is the fastest
|
||||
diagnosis, in the order set out in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## The schema, and the join that makes it useful
|
||||
|
||||
One row per bank, region, product, tier and observation, with footnotes as an array:
|
||||
|
||||
| field | why it earns its place |
|
||||
|---|---|
|
||||
| `min_balance` / `max_balance` | the tier, with null meaning open ended |
|
||||
| `rate_text` and parsed `rate` | the string survives a format change |
|
||||
| `rate_kind` | APY and APR are different quantities |
|
||||
| `footnotes` | resolved text, not markers |
|
||||
| `effective_text` | the bank's clock |
|
||||
| `observed_at` | yours, so staleness is measurable |
|
||||
|
||||
The analysis this shape enables, and that the banks' own pages cannot, is the one comparing
|
||||
a headline rate against its conditions over time. Introductory rates that quietly shorten
|
||||
their bonus period, tiers whose thresholds drift upward, and footnotes that gain a
|
||||
requirement between two captures are all visible as a diff, and all invisible in a table
|
||||
that keeps only the current best rate per product.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**What do the little superscript markers next to a rate mean?** They point at a
|
||||
footnote further down the page, and the footnote frequently carries the condition that
|
||||
makes the rate real: a minimum balance, a term, a new-money-only clause. Resolve the
|
||||
marker to its text at capture time, while the pointer is still in front of you.
|
||||
|
||||
**Is APR the same as APY?** No, and mixing them is the most common error in this data.
|
||||
Deposit products publish a yield that includes compounding; lending products publish a
|
||||
rate that does not. Read the column header into the row instead of hardcoding either.
|
||||
|
||||
**The rate table has bands. What is the row?** The tier. Tier bounds are part of the
|
||||
rate, and a null upper bound means the open-ended top band. Keep the tier text as
|
||||
written too, because banks describe the same band in words that do not always match
|
||||
the numbers.
|
||||
|
||||
**How fresh is a published rate?** Banks print an effective date, and it is the
|
||||
closest thing to a timestamp this data has. These pages are also cached hard, so the
|
||||
effective date and your fetch time can differ by days.
|
||||
|
||||
**See also:** [How to scrape geotargeted content with
|
||||
Playwright](how-to-scrape-geotargeted-content-playwright.md), [How to handle cookie
|
||||
consent banners in Playwright](how-to-handle-cookie-consent-banners-playwright.md),
|
||||
[How to scrape into a SQLite database with
|
||||
Playwright](how-to-scrape-into-a-database-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Locators, https://playwright.dev/python/docs/api/class-locator - driving
|
||||
a product or region picker that changes content with no URL change, and waiting for
|
||||
the table to repopulate before reading it.
|
||||
- This project's page on geotargeted content, which covers the region half of the same
|
||||
problem.
|
||||
@@ -13,7 +13,7 @@ To scrape business directory listings with Playwright, drive the search form for
|
||||
location-and-category pair, wait for the results to render, un-obfuscate the contact fields,
|
||||
and follow the site's own next control to walk the filtered pagination to its end. Run the
|
||||
whole city-by-category matrix under one pinned identity so it reads as a single visitor
|
||||
rather than a fleet of one-page strangers.
|
||||
instead of a fleet of one-page strangers.
|
||||
|
||||
A business directory looks like a flat list and behaves like a nested loop. There is no
|
||||
page you can request that returns every listing. There is a search form that wants a
|
||||
@@ -41,7 +41,7 @@ for city in cities:
|
||||
extract the listings on this page
|
||||
```
|
||||
|
||||
That structure is why a directory is throttled by identity rather than by request rate
|
||||
That structure is why a directory is throttled by identity, not by request rate
|
||||
alone. A human browsing the plumbers in one city visits a handful of pages. A full sweep
|
||||
visits every city crossed with every category, and every one of those is the same visitor
|
||||
asking a slightly different question. If that visitor's fingerprint changes between the
|
||||
@@ -50,7 +50,7 @@ watching a fleet of one-page strangers, which is a far cheaper thing to detect.
|
||||
|
||||
So the first design decision is to pin the identity for the whole sweep with a seed, and
|
||||
only vary the exit address deliberately. A fixed seed also makes the crawl replayable: if
|
||||
the extractor breaks on one category, you re-run the exact same browser rather than a new
|
||||
the extractor breaks on one category, you re-run the exact same browser instead of a new
|
||||
random one and get the same page back. That reproducibility is the whole reason
|
||||
[this project derives every surface from one seed](quickstart.md).
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
page.wait_for_selector("[data-testid='listing-card']")
|
||||
```
|
||||
|
||||
Waiting for a concrete element rather than a load event matters more here than on a static
|
||||
Waiting for a concrete element instead of a load event matters more here than on a static
|
||||
page, because the grid arrives after the document does. The difference between the load
|
||||
events and why `networkidle` misleads on a feed like this is covered in [how to wait for a
|
||||
page to load](how-to-wait-for-page-load-playwright.md); on a faceted search the honest
|
||||
|
||||
@@ -10,7 +10,7 @@ nav_order: 132
|
||||
# How to scrape fitness class schedules with Playwright
|
||||
|
||||
To scrape fitness class schedules with Playwright, read each row into a natural key
|
||||
of studio, class name, room and start time rather than trusting the row's own
|
||||
of studio, class name, room and start time instead of trusting the row's own
|
||||
occurrence id, fetch spots remaining and waitlist state from the separate endpoints
|
||||
that actually carry them instead of the rendered grid, walk the calendar forward one
|
||||
week per request because there is no week-agnostic feed, and stamp every pull with
|
||||
@@ -37,7 +37,7 @@ two behave identically until you diff two weeks and every row looks new.
|
||||
Do not build a pipeline that assumes the id survives. Build the key out of the facts
|
||||
that describe the slot itself: studio, class name, room and the ISO start time
|
||||
carries the schedule's meaning, and the occurrence id becomes metadata you store
|
||||
alongside it rather than the thing you key on.
|
||||
alongside it, not the thing you key on.
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
@@ -67,7 +67,7 @@ timezone is several surfaces a detector cross-checks, not one value.
|
||||
|
||||
## Set the site's location the way a visitor does
|
||||
|
||||
Drive the site's location selector rather than injecting a value. The selector is usually
|
||||
Drive the site's location selector instead of injecting a value. The selector is usually
|
||||
a control that opens, takes a typed city, and offers a suggestion to click:
|
||||
|
||||
```python
|
||||
@@ -87,7 +87,7 @@ a pointer that traveled to the control, which is
|
||||
|
||||
Once the feed is scoped, the cards are a repeating DOM structure and you read them in a
|
||||
loop. Because the feed is infinite and rotates, treat "how many cards" as "how many you
|
||||
scroll to", and dedupe on the listing's own id rather than on position, since positions
|
||||
scroll to", and dedupe on the listing's own id, not on position, since positions
|
||||
shift as new listings arrive:
|
||||
|
||||
```python
|
||||
@@ -146,7 +146,7 @@ for listing in list(seen.values()):
|
||||
```
|
||||
|
||||
That the click looks human is not a slogan here, it is the whole reason a patched engine
|
||||
is doing the driving. The pointer travels to the control on a curved path rather than
|
||||
is doing the driving. The pointer travels to the control on a curved path instead of
|
||||
teleporting, which is [what human mouse movement means in practice](human-mouse-movement.md),
|
||||
and the resulting event is trusted rather than synthetic. Space the reveals out. A hundred
|
||||
reveal clicks a minute from one session is a velocity signal no fingerprint can launder.
|
||||
|
||||
@@ -13,9 +13,9 @@ To scrape clinical trial listings with Playwright, timestamp every status read s
|
||||
status field decays between visits, carry both the registry's own identifier and any
|
||||
international identifier the same trial carries in a different country's registry, keep
|
||||
eligibility criteria as a list of text strings instead of parsed logic, store enrollment
|
||||
as a target figure with its actual-or-anticipated label rather than a headcount, extract
|
||||
as a target figure with its actual-or-anticipated label instead of a headcount, extract
|
||||
one recruiting status per listed site instead of one per trial, and log the absence of a
|
||||
results section as unreported rather than unfinished.
|
||||
results section as unreported, not unfinished.
|
||||
|
||||
A trial listing reads like a fact sheet and behaves like several records glued onto one
|
||||
page. The status line, the enrollment number, the site table and the results tab each
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
---
|
||||
title: "How to scrape conference agendas with Playwright"
|
||||
description: "Scrape conference schedules with Playwright: read a grid with parallel tracks without losing the track, resolve the event timezone once, and follow the session pages for speakers and abstracts."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 162
|
||||
---
|
||||
|
||||
|
||||
# How to scrape conference agendas with Playwright
|
||||
|
||||
To scrape an agenda, read the schedule as a **grid of tracks over time**, not as a
|
||||
list of sessions, and resolve the timezone once for the whole event. A conference agenda
|
||||
is one of the few web tables where position carries meaning: the column a session sits in
|
||||
is its track, and the rows above and below it are what it clashes with.
|
||||
|
||||
A list-shaped scrape loses that. It gives you every session with a start time and no way
|
||||
to answer the only question most people have, which is what runs against what.
|
||||
|
||||
This page covers reading the grid with its track intact, handling the timezone properly,
|
||||
and following through to the session pages where the speakers and abstracts live.
|
||||
|
||||
## Read the column, because the column is the track
|
||||
|
||||
Grid layouts put the track in a header, not in each cell. Read the header once, then map
|
||||
each session to the column it occupies:
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
GRID = """
|
||||
() => {
|
||||
const tracks = Array.from(document.querySelectorAll('.schedule-grid .track-header'))
|
||||
.map(h => h.textContent.trim());
|
||||
return Array.from(document.querySelectorAll('.schedule-grid .session')).map(s => {
|
||||
const col = Number(getComputedStyle(s).getPropertyValue('grid-column-start')) || null;
|
||||
return {
|
||||
title: s.querySelector('.session-title')?.textContent.trim() || null,
|
||||
start: s.dataset.start || null,
|
||||
end: s.dataset.end || null,
|
||||
href: s.querySelector('a')?.getAttribute('href') || null,
|
||||
track: col && tracks[col - 1] ? tracks[col - 1] : (s.dataset.track || null),
|
||||
};
|
||||
});
|
||||
}
|
||||
"""
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example-conf.com/schedule")
|
||||
page.wait_for_selector(".schedule-grid .session")
|
||||
sessions = page.evaluate(GRID)
|
||||
```
|
||||
|
||||
Reading `grid-column-start` from computed style is the trick that makes CSS-grid agendas
|
||||
tractable. The DOM order of sessions in these layouts is frequently meaningless, because
|
||||
the grid places them, so column position is the only reliable link between a session and
|
||||
its track header.
|
||||
|
||||
Where the site uses a data attribute for the track, prefer it and skip the geometry. Check
|
||||
both, because a redesign will switch between them.
|
||||
|
||||
## The timezone belongs to the event, not to you
|
||||
|
||||
Agendas print local times without zones almost universally. Resolve the event's zone once
|
||||
and attach it, not letting each row inherit whatever your machine thinks:
|
||||
|
||||
```python
|
||||
tz = page.eval_on_selector(
|
||||
"meta[name='event-timezone'], .event-timezone",
|
||||
"e => e.content || e.textContent.trim()",
|
||||
) if page.query_selector("meta[name='event-timezone'], .event-timezone") else None
|
||||
row["event_timezone"] = tz # e.g. "Europe/Lisbon"
|
||||
```
|
||||
|
||||
When the page does not say, take it from the venue city and record that you inferred it.
|
||||
An agenda stored in naive local time is usable; one silently converted to your machine's
|
||||
zone is a schedule that is wrong by hours for everyone who reads it later, and there is
|
||||
nothing in the data that reveals the error.
|
||||
|
||||
Hybrid and online events make this worse by publishing two schedules, one in venue time
|
||||
and one in the viewer's, sometimes switched by a toggle. Pin the toggle explicitly and
|
||||
record which one you read.
|
||||
|
||||
## Sessions are stubs; the detail page has the substance
|
||||
|
||||
The grid cell carries a title and a time. Speakers, abstract, room and level live on the
|
||||
session page:
|
||||
|
||||
```python
|
||||
def session_detail(page, href):
|
||||
page.goto(href)
|
||||
page.wait_for_selector(".session-detail")
|
||||
return {
|
||||
"abstract": page.inner_text(".session-abstract"),
|
||||
"room": page.inner_text(".session-room") if page.query_selector(".session-room") else None,
|
||||
"speakers": [{
|
||||
"name": s.query_selector(".speaker-name").inner_text().strip(),
|
||||
"affiliation": (s.query_selector(".speaker-affiliation").inner_text().strip()
|
||||
if s.query_selector(".speaker-affiliation") else None),
|
||||
} for s in page.query_selector_all(".speaker")],
|
||||
}
|
||||
```
|
||||
|
||||
Keep speakers as a list of objects instead of a joined string. A comma-separated field
|
||||
looks fine until a name contains a comma, and academic affiliations contain commas
|
||||
constantly.
|
||||
|
||||
## Multi-day tabs and the day you did not read
|
||||
|
||||
Agendas split by day, behind tabs that swap the grid without changing the URL. The failure
|
||||
is quiet: you scrape one day and get a complete-looking dataset:
|
||||
|
||||
```python
|
||||
for tab in page.query_selector_all(".day-tabs [role='tab']"):
|
||||
day = tab.inner_text().strip()
|
||||
tab.click()
|
||||
page.wait_for_selector(".schedule-grid .session")
|
||||
for s in page.evaluate(GRID):
|
||||
s["day"] = day
|
||||
```
|
||||
|
||||
This is the same mechanic as any
|
||||
[tab or accordion panel](how-to-scrape-accordion-and-tab-content-playwright.md), and the
|
||||
same rule applies: click the control, wait for the content, do not guess a URL.
|
||||
|
||||
## Agendas change until the morning of the event
|
||||
|
||||
Schedules are edited constantly in the final weeks: rooms move, speakers cancel, sessions
|
||||
swap slots. If the change history matters to you, keep each capture whole with its
|
||||
timestamp instead of updating rows in place, and diff captures later. If it does not,
|
||||
a daily pass in the fortnight before the event, and one after it, is enough.
|
||||
|
||||
Either way this is a small site with a spiky audience, so keep to the pacing in
|
||||
[rate limiting your own scraper](how-to-rate-limit-your-scraper-playwright.md) and prefer
|
||||
running outside the conference hours themselves, when the site is serving the people
|
||||
actually at the event.
|
||||
|
||||
## A complete capture, days and sessions
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
def capture_agenda(page, url):
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
page.wait_for_selector(".schedule-grid .session", timeout=20000)
|
||||
|
||||
tz_node = page.query_selector("meta[name='event-timezone'], .event-timezone")
|
||||
tz = page.evaluate("e => e.content || e.textContent.trim()", tz_node) if tz_node else None
|
||||
|
||||
days, sessions = page.query_selector_all(".day-tabs [role='tab']"), []
|
||||
if not days:
|
||||
for s in page.evaluate(GRID):
|
||||
sessions.append({**s, "day": None})
|
||||
else:
|
||||
for tab in days:
|
||||
label = tab.inner_text().strip()
|
||||
tab.click()
|
||||
page.wait_for_function(
|
||||
"() => document.querySelectorAll('.schedule-grid .session').length > 0")
|
||||
page.wait_for_timeout(400) # let the grid settle after the swap
|
||||
for s in page.evaluate(GRID):
|
||||
sessions.append({**s, "day": label})
|
||||
|
||||
return {"url": url, "event_timezone": tz,
|
||||
"captured_at": time.time(), "sessions": sessions}
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("agenda.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
agenda = capture_agenda(page, "https://example-conf.com/schedule")
|
||||
out.write(json.dumps(agenda, ensure_ascii=False) + "\n")
|
||||
|
||||
for session in agenda["sessions"]:
|
||||
if not session.get("href"):
|
||||
continue
|
||||
detail = session_detail(page, session["href"])
|
||||
out.write(json.dumps({"session_href": session["href"], **detail,
|
||||
"captured_at": time.time()}, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(1500)
|
||||
```
|
||||
|
||||
Writing the whole agenda as one record per capture, rather than one row per session, is
|
||||
deliberate. Agendas are edited constantly in the final fortnight, and the interesting
|
||||
analysis is the diff between two captures: which sessions moved, which speakers dropped,
|
||||
which rooms changed. A row-per-session table updated in place erases exactly that.
|
||||
|
||||
## Why conference sites break in the last two weeks
|
||||
|
||||
These are usually built quickly on a platform, deployed once, and then edited under
|
||||
pressure. The failures are not defences.
|
||||
|
||||
**The grid is rebuilt on every tab click.** Elements captured before the click are detached
|
||||
afterwards, so a Python-side loop holding handles across a tab change throws or reads
|
||||
stale nodes. Capturing each day in one evaluation, as above, avoids the whole class.
|
||||
|
||||
**Session pages 404 while the grid still lists them.** A withdrawn talk is removed from the
|
||||
detail route before the schedule is regenerated. Record the failure as a row rather than
|
||||
letting it stop the run, and the disappearance becomes data about the event.
|
||||
|
||||
**The timezone toggle changes the grid under you.** Hybrid events render either venue time
|
||||
or viewer time, and the control sometimes defaults from a stored preference. Read the
|
||||
resolved zone back after setting it rather than assuming, which is the same verify-the-lever
|
||||
discipline that applies to the unit toggles on other targets.
|
||||
|
||||
Where a platform does put the schedule behind protection, which a few of the larger ones
|
||||
do, the page is worth a look before assuming a selector problem, using the order in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## The shape that answers scheduling questions
|
||||
|
||||
From captures, derive two tables:
|
||||
|
||||
| table | key | holds |
|
||||
|---|---|---|
|
||||
| `session` | `event`, `day`, `track`, `start` | title, room, href, first and last seen |
|
||||
| `speaker` | `session_id`, `name` | affiliation, ordinal |
|
||||
|
||||
Keeping speakers in their own table rather than a joined string is what makes the useful
|
||||
queries possible: who appears most across tracks, which affiliations dominate a programme,
|
||||
whether a speaker is double-booked against themselves. The last one happens more often than
|
||||
organisers would like, and it is only visible when track and time are both kept.
|
||||
|
||||
The clash query is the one that justifies the grid work at the start of this page. Two
|
||||
sessions clash when they share a day and overlap in time on different tracks, and that is a
|
||||
single join once the track is a real column rather than a heading you read past.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Where does the track name live in a grid agenda?** In the column header, once, and
|
||||
not in the cells. Read the header first and map each session to its column, or every
|
||||
session arrives without the one field that makes a grid a schedule.
|
||||
|
||||
**The agenda prints times with no timezone. Which one applies?** The event's,
|
||||
essentially always. Agendas print local times bare, so resolve the event zone once and
|
||||
attach it to every session; your own machine's zone is the wrong answer and the
|
||||
easiest one to record by accident.
|
||||
|
||||
**Why is my capture missing half the sessions?** Because the agenda splits by day
|
||||
behind tabs that swap the grid without changing the URL. The failure is quiet: you get
|
||||
a full, valid, complete-looking grid for one day.
|
||||
|
||||
**How stable is a conference agenda?** Not stable at all in the final weeks. Rooms
|
||||
move, speakers cancel and sessions swap slots up to the morning of the event, which is
|
||||
why a capture is stored as a dated record and not as the truth.
|
||||
|
||||
**See also:** [How to scrape accordion and tab content with
|
||||
Playwright](how-to-scrape-accordion-and-tab-content-playwright.md), [How to rate limit
|
||||
your own Playwright scraper](how-to-rate-limit-your-scraper-playwright.md), [How to
|
||||
scrape without getting blocked](how-to-scrape-without-getting-blocked.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- MDN, the `time` element,
|
||||
https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/time - the
|
||||
`datetime` attribute as the machine-readable form of a printed time, checked for
|
||||
where an agenda may carry a zone the visible text omits.
|
||||
- Playwright, Locators, https://playwright.dev/python/docs/api/class-locator - reading
|
||||
a header row once and mapping cells to it, and driving tabs that swap content
|
||||
without a navigation.
|
||||
@@ -0,0 +1,263 @@
|
||||
---
|
||||
title: "How to scrape construction permit records with Playwright"
|
||||
description: "Scrape municipal permit portals with Playwright: drive the postback search forms these systems use, page through result sets that only exist in a session, and keep the permit status history."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 159
|
||||
---
|
||||
|
||||
|
||||
# How to scrape construction permit records with Playwright
|
||||
|
||||
To scrape a permit portal, drive its **search form** and stay in the session it gives you.
|
||||
These systems are almost always server-rendered enterprise software, where the results
|
||||
page is a postback instead of a URL, page two is a form submission, and a link copied out
|
||||
of the browser returns a session-expired notice ten minutes later.
|
||||
|
||||
That single property decides the whole design. You cannot build a list of URLs and fetch
|
||||
them in parallel. You drive one session in order, and you make it resumable, because a
|
||||
run over a year of permits takes long enough that something will interrupt it.
|
||||
|
||||
This page covers filling the search the way the form expects, walking result pages that
|
||||
only exist inside a session, and capturing a permit's status history, not its
|
||||
current state.
|
||||
|
||||
## Fill the search in the order the form expects
|
||||
|
||||
Permit searches are usually date-range plus type, and the fields depend on each other:
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://permits.example.gov/search")
|
||||
|
||||
page.select_option("select#permitType", "BUILDING")
|
||||
page.fill("input#dateFrom", "01/01/2026")
|
||||
page.fill("input#dateTo", "01/31/2026")
|
||||
page.click("input#btnSearch")
|
||||
page.wait_for_selector("#resultsGrid tr, .no-records")
|
||||
```
|
||||
|
||||
Select the type before the dates where the form reloads on change. Many of these pages
|
||||
issue a postback when a dropdown changes, which clears fields filled before it, so the
|
||||
order that works is the order a person would use: the thing that reshapes the form first,
|
||||
the details after.
|
||||
|
||||
If the date fields are pickers that ignore typed values, treat them as
|
||||
[date-picker calendars](how-to-scrape-date-picker-calendar-playwright.md) and click the
|
||||
days.
|
||||
|
||||
## Page two is a form submission, not a URL
|
||||
|
||||
```python
|
||||
def next_page(page):
|
||||
link = page.query_selector("a#nextPage:not(.disabled)")
|
||||
if not link:
|
||||
return False
|
||||
first_before = page.inner_text("#resultsGrid tr:nth-child(1)")
|
||||
link.click()
|
||||
page.wait_for_function(
|
||||
"prev => document.querySelector('#resultsGrid tr').innerText !== prev",
|
||||
arg=first_before,
|
||||
)
|
||||
return True
|
||||
```
|
||||
|
||||
Waiting for the first row to change is the reliable signal. Waiting for a navigation
|
||||
returns immediately on a page that never navigates, and waiting a fixed time either wastes
|
||||
seconds or reads the previous page. The general shape is the one in
|
||||
[scraping paginated pages](how-to-scrape-paginated-pages-playwright.md), with the extra
|
||||
constraint that here you genuinely cannot skip ahead.
|
||||
|
||||
Narrow the query instead of paging deeply. Most portals cap results, often silently, at a
|
||||
few hundred rows. A month at a time with an explicit row count check is more work and
|
||||
returns the whole set:
|
||||
|
||||
```python
|
||||
total = page.inner_text(".result-count") # "1 to 25 of 412"
|
||||
```
|
||||
|
||||
Compare the total against what you collected and fail loudly on a mismatch. A silent cap
|
||||
is the most common way these datasets end up missing a third of a year.
|
||||
|
||||
## Capture the status history, not just the current status
|
||||
|
||||
A permit moves through review stages, and the interesting questions are about duration:
|
||||
how long between application and issue, where files stall, which reviewers are backed up.
|
||||
The detail page usually carries this as a table:
|
||||
|
||||
```python
|
||||
def permit_detail(page, href):
|
||||
page.click(f"a[href='{href}']")
|
||||
page.wait_for_selector("#permitDetail")
|
||||
stages = []
|
||||
for tr in page.query_selector_all("#statusHistory tbody tr"):
|
||||
cells = [td.inner_text().strip() for td in tr.query_selector_all("td")]
|
||||
stages.append({"stage": cells[0], "date": cells[1], "outcome": cells[2] if len(cells) > 2 else None})
|
||||
return stages
|
||||
```
|
||||
|
||||
If the portal only shows a current status, capture it with your run timestamp and build
|
||||
the history yourself across runs. That is slower to become useful, and it is the only way
|
||||
to get duration data out of a system that does not publish it.
|
||||
|
||||
## Make the run resumable, because it will be interrupted
|
||||
|
||||
A session-bound sequential crawl over months of records is exactly the job that dies at
|
||||
70%. Write each page as you go and record where you were:
|
||||
|
||||
```python
|
||||
checkpoint = {"type": "BUILDING", "from": "01/01/2026", "to": "01/31/2026", "page": 7}
|
||||
```
|
||||
|
||||
Then a restart re-runs the search and pages forward to the checkpoint rather than starting
|
||||
over. The pattern and its edge cases are in
|
||||
[resuming an interrupted scrape](how-to-resume-an-interrupted-scrape-playwright.md), and
|
||||
[retrying failed requests](how-to-retry-failed-requests-playwright.md) covers the
|
||||
transient failures that make it necessary.
|
||||
|
||||
## These are public records, and they contain people
|
||||
|
||||
Permit data is published deliberately, and it is genuinely useful: construction activity,
|
||||
contractor patterns, neighbourhood change. It also contains owner names and addresses,
|
||||
which are personal data in most jurisdictions regardless of being publicly displayed.
|
||||
|
||||
Take the fields your question needs rather than the whole record by default, keep the
|
||||
retention deliberate, and check whether the jurisdiction already publishes a bulk export.
|
||||
Many do, on an open data portal, and pulling a file is better for everyone than paging a
|
||||
search form for a week. The technique for those is in
|
||||
[scraping open data portals](how-to-scrape-open-data-portals-playwright.md).
|
||||
|
||||
## A complete month-by-month sweep
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from datetime import date
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
def months(start_year, start_month, count):
|
||||
y, m = start_year, start_month
|
||||
for _ in range(count):
|
||||
nxt_y, nxt_m = (y, m + 1) if m < 12 else (y + 1, 1)
|
||||
yield date(y, m, 1), date(nxt_y, nxt_m, 1)
|
||||
y, m = nxt_y, nxt_m
|
||||
|
||||
def sweep_month(page, permit_type, first, nxt):
|
||||
page.goto("https://permits.example.gov/search")
|
||||
page.select_option("select#permitType", permit_type)
|
||||
page.fill("input#dateFrom", first.strftime("%m/%d/%Y"))
|
||||
page.fill("input#dateTo", (nxt - timedelta(days=1)).strftime("%m/%d/%Y"))
|
||||
page.click("input#btnSearch")
|
||||
page.wait_for_selector("#resultsGrid tr, .no-records")
|
||||
|
||||
if page.query_selector(".no-records"):
|
||||
return [], 0
|
||||
|
||||
total_text = page.inner_text(".result-count") # "1 to 25 of 412"
|
||||
total = int(total_text.rsplit(" ", 1)[-1].replace(",", ""))
|
||||
rows = []
|
||||
while True:
|
||||
rows.extend(read_grid(page))
|
||||
if not next_page(page):
|
||||
break
|
||||
return rows, total
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("permits.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
for first, nxt in months(2026, 1, 12):
|
||||
rows, total = sweep_month(page, "BUILDING", first, nxt)
|
||||
if total and len(rows) != total:
|
||||
raise SystemExit(f"{first:%Y-%m}: collected {len(rows)} of {total}, refusing to continue")
|
||||
for row in rows:
|
||||
out.write(json.dumps({**row, "month": f"{first:%Y-%m}",
|
||||
"observed_at": time.time()}, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(4000)
|
||||
```
|
||||
|
||||
The count assertion is the most valuable line in the sweep. These portals cap silently,
|
||||
and a month that quietly returns 200 of 412 permits produces a dataset that looks complete
|
||||
and is missing half the construction in a city. Failing loudly there costs you a rerun;
|
||||
not checking costs you the conclusion.
|
||||
|
||||
## Government portals fail politely and confusingly
|
||||
|
||||
These systems are not defending against you in the adversarial sense. They are old, they
|
||||
are shared, and they degrade in ways that look like data.
|
||||
|
||||
**The session times out mid-sweep.** After a pause the next postback returns the search
|
||||
form rather than results, which reads as a month with no permits. Detect it by asserting
|
||||
the results grid or the no-records marker exists after every submission, and re-establish
|
||||
the session rather than recording an absence.
|
||||
|
||||
**Business hours matter more than rate limits.** Many of these portals are slow enough
|
||||
during working hours that a page load exceeds a naive timeout, and fine overnight. Running
|
||||
outside the jurisdiction's hours is both faster for you and invisible to the staff who
|
||||
depend on the same server.
|
||||
|
||||
**The grid renders before it fills.** Waiting for `#resultsGrid tr` matches the header row
|
||||
on several platforms. Wait for a row that carries a permit number:
|
||||
|
||||
```python
|
||||
page.wait_for_function(
|
||||
"() => document.querySelectorAll('#resultsGrid tr td:first-child').length > 0"
|
||||
)
|
||||
```
|
||||
|
||||
Where a portal does sit behind commodity edge protection, which a minority do, the browser
|
||||
still needs to look like a browser for the search to run at all, and the debug order is
|
||||
in [scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## Two tables, and the durations they unlock
|
||||
|
||||
Keep the permit and its status history separately:
|
||||
|
||||
| table | key | holds |
|
||||
|---|---|---|
|
||||
| `permit` | `jurisdiction`, `permit_number` | type, address, valuation, contractor, applicant |
|
||||
| `stage` | `permit_number`, `sequence` | stage name, date, outcome |
|
||||
|
||||
The second table is where the value is. With stages, you can compute time from application
|
||||
to issue, find which review stage holds files longest, and see whether a backlog is growing
|
||||
or clearing. Those questions are why permit data is scraped at all, and none of them are
|
||||
answerable from a table of current statuses.
|
||||
|
||||
On the personal data, one practical default: keep `contractor` and drop `applicant` unless
|
||||
your question genuinely needs the individual. Contractor activity is commercial and is the
|
||||
subject of most legitimate analysis; applicant names are the part that makes a permit
|
||||
dataset a dataset about people.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why does my search return nothing when the same query works by hand?** Order. Permit
|
||||
search forms have dependent fields, and a type or status list only populates after the
|
||||
date range or the jurisdiction is set. Filling them out of order leaves a control
|
||||
empty and the search runs against a filter that was never applied.
|
||||
|
||||
**Page two does nothing when I change the URL. Why?** Because paging is a form
|
||||
submission, not a navigation. Click the control and wait for the first row to change;
|
||||
waiting for a navigation returns immediately and you read page one twice.
|
||||
|
||||
**Should I capture the current status or the whole history?** The history. These
|
||||
records exist to answer questions about duration - how long a permit sat in each
|
||||
review stage - and a single current status cannot answer any of them.
|
||||
|
||||
**How do I know the portal is not silently capping my results?** Ask it for the count
|
||||
and compare. These systems cap without saying so, and a month that returns exactly the
|
||||
cap is a month you have not actually read.
|
||||
|
||||
**See also:** [Scrape a multi-step wizard flow with
|
||||
Playwright](how-to-scrape-multi-step-wizard-flow-playwright.md), [How to resume an
|
||||
interrupted scrape with
|
||||
Playwright](how-to-resume-an-interrupted-scrape-playwright.md), [How to retry failed
|
||||
requests when scraping Playwright](how-to-retry-failed-requests-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Locators, https://playwright.dev/python/docs/api/class-locator - waiting
|
||||
for content to change after a form submission rather than waiting for a navigation,
|
||||
checked for the paging behaviour these portals use.
|
||||
- This project's page on resuming an interrupted scrape, which this page depends on
|
||||
because a months-long sequential crawl is the job that dies partway through.
|
||||
@@ -9,7 +9,7 @@ nav_order: 94
|
||||
|
||||
# How to scrape course catalogs with Playwright
|
||||
|
||||
To scrape a course catalog with Playwright, treat it as a four-level tree rather than a
|
||||
To scrape a course catalog with Playwright, treat it as a four-level tree instead of a
|
||||
list of courses: walk department to course to section to meeting time, pin the term in
|
||||
the query string so every request describes the same academic period, read seat counts
|
||||
from the section endpoint instead of the rendered badge, and emit one row per section so
|
||||
@@ -79,7 +79,7 @@ Put the term in the URL and never rely on the session:
|
||||
page.goto(f"{base}/search?term={term}&subject={dept}", wait_until="domcontentloaded")
|
||||
```
|
||||
|
||||
If the catalog keeps the term in a cookie or a POST body rather than the query string,
|
||||
If the catalog keeps the term in a cookie or a POST body, not the query string,
|
||||
set it once per context and assert it on every response before parsing. The assertion is
|
||||
cheap and the alternative is a silently mixed dataset.
|
||||
|
||||
@@ -92,7 +92,7 @@ The green "Open" pill on the results page is a rendering of a number the page al
|
||||
fetched. It is rounded, it is cached, and on many catalogs it stops updating once the
|
||||
section closes. The underlying call carries the real integers.
|
||||
|
||||
Capture the response rather than the pixel:
|
||||
Capture the response instead of the pixel:
|
||||
|
||||
```python
|
||||
seats = {}
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
---
|
||||
title: "How to scrape court docket listings with Playwright"
|
||||
description: "Scrape public court dockets with Playwright: work case by case, not by enumeration, capture the docket entries as an ordered record, and handle the documents that open in a viewer."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 160
|
||||
---
|
||||
|
||||
|
||||
# How to scrape court docket listings with Playwright
|
||||
|
||||
To scrape a public docket, work from **case numbers you already have** and capture the
|
||||
docket entries as an ordered list. A docket is a chronological record of filings, and its
|
||||
value is the sequence: what was filed, when, by which party, and what the court did next.
|
||||
The case summary at the top is a rollup of that sequence and loses the timing.
|
||||
|
||||
The other thing to settle before writing code is scope. Court systems publish these
|
||||
records deliberately, and they also rate limit hard, because enumeration is a known abuse
|
||||
pattern. A scraper that walks a case number space is doing the thing the defences exist
|
||||
for, and it will be stopped. One that resolves a list of cases it has a reason to hold
|
||||
behaves like a researcher and generally works.
|
||||
|
||||
This page covers driving the case lookup, reading the docket sheet, and dealing with the
|
||||
documents attached to entries.
|
||||
|
||||
## Look up cases you already identified
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
def open_case(page, case_number):
|
||||
page.goto("https://courts.example.gov/case-search")
|
||||
page.fill("input#caseNumber", case_number)
|
||||
page.click("button#search")
|
||||
page.wait_for_selector("#docketSheet, .case-not-found")
|
||||
return page.query_selector("#docketSheet") is not None
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
for case_number in known_cases:
|
||||
if open_case(page, case_number):
|
||||
rows = docket_entries(page)
|
||||
```
|
||||
|
||||
Keep the not-found branch explicit. Sealed, expunged and simply mistyped cases all render
|
||||
as an absence, and conflating them with an empty docket produces a dataset that quietly
|
||||
asserts cases had no activity.
|
||||
|
||||
## The docket sheet is an ordered record
|
||||
|
||||
```python
|
||||
def docket_entries(page):
|
||||
entries = []
|
||||
for tr in page.query_selector_all("#docketSheet tbody tr"):
|
||||
cells = [td.inner_text().strip() for td in tr.query_selector_all("td")]
|
||||
if len(cells) < 3:
|
||||
continue
|
||||
entries.append({
|
||||
"sequence": cells[0],
|
||||
"filed": cells[1],
|
||||
"text": cells[2],
|
||||
"documents": [a.get_attribute("href")
|
||||
for a in tr.query_selector_all("a[href]")],
|
||||
})
|
||||
return entries
|
||||
```
|
||||
|
||||
Keep the court's sequence number as given, and do not renumber. Courts skip numbers, add
|
||||
entries out of order after the fact, and use suffixes such as `12-1` for related filings.
|
||||
Your own index built by enumeration will silently disagree with every citation anyone
|
||||
writes against that docket.
|
||||
|
||||
Store `text` verbatim. Docket text is terse legal shorthand written by clerks, and any
|
||||
normalisation loses information that a lawyer reading the row will need.
|
||||
|
||||
## Documents open in a viewer, not as a download
|
||||
|
||||
Attachments on these systems usually open a PDF in a viewer tab rather than downloading.
|
||||
That is a specific mechanic worth handling deliberately, and it is the same one described
|
||||
in [when a PDF opens in a new tab](how-to-handle-pdf-opens-new-tab-playwright.md).
|
||||
|
||||
Where documents are behind a paywall or a per-page fee, which is common, stop at the
|
||||
metadata. The entry text plus the document reference is usually enough to answer questions
|
||||
about activity and timing, and it avoids both the cost and the licensing question that
|
||||
comes with mirroring court documents. If you do fetch documents you are entitled to,
|
||||
[downloading linked PDFs](how-to-scrape-linked-pdfs-playwright.md) covers doing it through
|
||||
the browser session rather than a side client.
|
||||
|
||||
## Pace it slowly and deliberately
|
||||
|
||||
Court portals are among the strictest rate limiters in public web infrastructure, and for
|
||||
good reason. A pace of one case every several seconds, with a hard daily cap, is both
|
||||
respectful and the pace that keeps working:
|
||||
|
||||
```python
|
||||
import time
|
||||
for case_number in known_cases[:200]: # a cap, not a full sweep
|
||||
...
|
||||
time.sleep(5)
|
||||
```
|
||||
|
||||
The reasoning behind self-imposed limits, and why they beat waiting to be blocked, is in
|
||||
[rate limiting your own scraper](how-to-rate-limit-your-scraper-playwright.md). Run
|
||||
overnight in the court's timezone where you can: these systems are used by people doing
|
||||
their jobs during the day.
|
||||
|
||||
## The parts to leave alone
|
||||
|
||||
Three things on these systems are worth naming as out of scope, not because they are hard
|
||||
but because taking them is the difference between research and harm.
|
||||
|
||||
**Do not enumerate.** Walking a case number range harvests the cases of people who are not
|
||||
your subject, including sealed matters that leak through misconfiguration.
|
||||
|
||||
**Do not aggregate people.** A docket is public; a compiled profile of every case a named
|
||||
individual appears in is a different artefact with different consequences, and several
|
||||
jurisdictions treat it as such in law.
|
||||
|
||||
**Do not re-publish documents wholesale.** Court records frequently contain personal
|
||||
identifiers that the court expects a human reader to see one at a time.
|
||||
|
||||
Scraping dockets for a defined question, on cases you can name, is the version of this
|
||||
that is both legal in most places and defensible. Store it in something queryable such as
|
||||
[a SQLite database](how-to-scrape-into-a-database-playwright.md), keep the raw entry text,
|
||||
and keep the run's own metadata so you can say later exactly what you asked and when.
|
||||
|
||||
## A complete run over a named case list
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
CASES = ["2026-CV-001234", "2026-CV-001987"] # cases you can name and justify
|
||||
PACE_SECONDS, DAILY_CAP = 6, 200
|
||||
|
||||
def already_done(path):
|
||||
seen = set()
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
seen.add(json.loads(line)["case_number"])
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
return seen
|
||||
|
||||
path = "dockets.jsonl"
|
||||
done = already_done(path)
|
||||
budget = DAILY_CAP
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open(path, "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
for case_number in CASES:
|
||||
if case_number in done or budget <= 0:
|
||||
continue
|
||||
found = open_case(page, case_number)
|
||||
record = {
|
||||
"case_number": case_number,
|
||||
"observed_at": time.time(),
|
||||
"found": found,
|
||||
"entries": docket_entries(page) if found else [],
|
||||
}
|
||||
if not found:
|
||||
note = page.query_selector(".case-not-found")
|
||||
record["not_found_text"] = note.inner_text().strip() if note else None
|
||||
out.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
budget -= 1
|
||||
time.sleep(PACE_SECONDS)
|
||||
```
|
||||
|
||||
The daily cap is written into the loop rather than left to discipline. A court portal that
|
||||
decides you are abusive does not send a warning, and the cap is what keeps a long research
|
||||
project from ending on its second day.
|
||||
|
||||
Keeping the `not_found_text` verbatim matters more here than elsewhere: sealed, expunged,
|
||||
transferred and mistyped all produce different wording, and that wording is the only
|
||||
evidence you will have about which one it was.
|
||||
|
||||
## What these systems do when they decide you are a problem
|
||||
|
||||
Court portals sit at the strict end of public infrastructure, and their responses are worth
|
||||
recognising because two of the three look like ordinary results.
|
||||
|
||||
**A silent empty docket.** The case page renders with no entries rather than an error. Since
|
||||
a genuinely new case also has few entries, the difference is invisible unless you compare
|
||||
against a previous read. A case that had thirty entries yesterday and none today is a
|
||||
failed read, not a purged docket:
|
||||
|
||||
```python
|
||||
if previous.get(case_number) and not record["entries"]:
|
||||
record["suspect"] = "entries vanished from a docket that had them"
|
||||
```
|
||||
|
||||
**An interstitial that consumes the click.** Several portals put a terms page in front of
|
||||
the first search per session and again after a period of inactivity. A run that does not
|
||||
re-check for it after a pause submits its search into a page that is not the search page.
|
||||
|
||||
**A hard block on the address.** This is the honest end state of ignoring the pace, and it
|
||||
is usually not reversible by waiting a few minutes. The general diagnosis order is in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md), but the
|
||||
specific advice for court systems is different from most targets: the fix is almost always
|
||||
to slow down and narrow the question, not to look more like a browser.
|
||||
|
||||
## The schema, and the retention decision that comes with it
|
||||
|
||||
| table | key | holds |
|
||||
|---|---|---|
|
||||
| `case` | `court`, `case_number` | caption, type, filed date, current status |
|
||||
| `entry` | `court`, `case_number`, `sequence` | filed date, verbatim text, document references |
|
||||
| `run` | `run_id` | what was asked, when, and under what cap |
|
||||
|
||||
The `run` table is unusual and worth keeping. Docket research is the kind of work where
|
||||
someone may later ask what you collected and why, and a log of the queries you made is a
|
||||
better answer than a reconstruction from the data.
|
||||
|
||||
For retention, the defensible default is to keep the entries you analysed and drop the
|
||||
rest, rather than accumulating dockets because they were cheap to fetch. The value of this
|
||||
data is in answering a specific question about court activity; the risk in it is that a
|
||||
general archive of dockets is a general archive about people, and the second grows quietly
|
||||
out of the first if nobody decides otherwise.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Can I search for cases by name?** This page does not, and that is deliberate. It
|
||||
looks up cases already identified by number. Bulk identification of people through a
|
||||
court portal is a different activity with different consequences.
|
||||
|
||||
**Why is the docket numbering full of gaps?** Because courts skip numbers, add entries
|
||||
out of sequence and amend them later. Keep the court's sequence number exactly as
|
||||
given and never renumber: the gaps are part of the record.
|
||||
|
||||
**The document did not download, it opened in a viewer.** That is the normal behaviour
|
||||
on these systems: attachments open a PDF in a viewer tab instead of triggering a
|
||||
download, so the download-handling route does not apply.
|
||||
|
||||
**A case returned nothing. Does that mean it does not exist?** Not necessarily.
|
||||
Sealed, expunged and mistyped cases all render as the same absence, so keep the
|
||||
not-found branch explicit instead of treating it as an empty result.
|
||||
|
||||
**See also:** [How to Handle a PDF That Opens in a New Tab with
|
||||
Playwright](how-to-handle-pdf-opens-new-tab-playwright.md), [Download and read PDFs
|
||||
linked from a page with Playwright](how-to-scrape-linked-pdfs-playwright.md), [How to
|
||||
rate limit your own Playwright scraper](how-to-rate-limit-your-scraper-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Network, https://playwright.dev/python/docs/network - request
|
||||
interception and response capture, checked for the case where a document opens in a
|
||||
viewer instead of arriving as a download.
|
||||
- This project's pages on PDFs that open in a new tab and on scraping linked PDFs,
|
||||
which carry the mechanics this page points at instead of repeating them.
|
||||
@@ -14,7 +14,7 @@ WebSocket and read each price from the frames it delivers, not from the DOM node
|
||||
live ticker overwrites that node several times a second, so the value you read back is
|
||||
stale the instant you have it. Handle the ranked market-cap table as a separate
|
||||
scroll-and-collect job, and hold the connection open with a stable browser identity so
|
||||
that a dropped-and-reconnected feed reads as one steady client rather than a churn of
|
||||
that a dropped-and-reconnected feed reads as one steady client instead of a churn of
|
||||
new devices.
|
||||
|
||||
Before writing a line of code, though: if the exchange or aggregator you are reading
|
||||
@@ -26,8 +26,8 @@ and you have to get them out of a live browser without capturing garbage.
|
||||
That case is harder than it looks, for a reason specific to prices: they do not sit
|
||||
still. A crypto ticker updates many times a second over a persistent WebSocket, and
|
||||
the number you see in the DOM is the tail end of a stream that has already moved on by
|
||||
the time your `text_content()` call returns. This page is about reading the stream
|
||||
rather than the tail, paging the market table as a separate job, and keeping the
|
||||
the time your `text_content()` call returns. This page is about reading the stream,
|
||||
not the tail, paging the market table as a separate job, and keeping the
|
||||
connection alive long enough to matter.
|
||||
|
||||
## Why the DOM value is a race you lose
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
---
|
||||
title: "How to scrape CSS pseudo-element content with Playwright"
|
||||
description: "Read text injected by ::before and ::after with Playwright: it is not in the DOM and inner_text will not return it, so query the computed style instead."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 169
|
||||
---
|
||||
|
||||
|
||||
# How to scrape CSS pseudo-element content with Playwright
|
||||
|
||||
Text injected by `::before` and `::after` is **not in the DOM**, so `inner_text` and
|
||||
`text_content` will never return it. Read it with
|
||||
[`getComputedStyle`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle)
|
||||
passing the pseudo-element as the second argument, and read the `content` property.
|
||||
|
||||
This catches people because the text is plainly visible on screen. You can select it in
|
||||
some browsers, you can screenshot it, and every DOM-based extraction returns an empty
|
||||
string. Nothing errors, which is the worst version of the problem: the row is written with
|
||||
a blank field and the run reports success.
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example.com/product/1234")
|
||||
|
||||
value = page.eval_on_selector(
|
||||
".badge",
|
||||
"el => getComputedStyle(el, '::after').content",
|
||||
)
|
||||
print(value) # '"In stock"' including the quotes
|
||||
```
|
||||
|
||||
## The value comes back quoted, and sometimes as none
|
||||
|
||||
`content` is a CSS value, not a string, so it arrives with its quotation marks and needs
|
||||
unwrapping. It can also be the keyword `none` when no rule applies, and `normal` on
|
||||
elements where the pseudo-element does not generate a box:
|
||||
|
||||
```python
|
||||
def pseudo_text(page, selector, pseudo="::after"):
|
||||
raw = page.eval_on_selector(
|
||||
selector,
|
||||
"(el, p) => getComputedStyle(el, p).content",
|
||||
pseudo,
|
||||
)
|
||||
if raw in (None, "none", "normal", '""'):
|
||||
return None
|
||||
if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'":
|
||||
return raw[1:-1]
|
||||
return raw
|
||||
```
|
||||
|
||||
Returning `None` for `none` matters. An empty string and an absent pseudo-element are
|
||||
different facts, and only the second means the rule did not apply to this element.
|
||||
|
||||
## Four things `content` can hold besides text
|
||||
|
||||
The property is more expressive than a string, and each form needs different handling:
|
||||
|
||||
- **A literal string**, which is the common case above.
|
||||
- **An `attr()` reference**, such as `content: attr(data-label)`. Computed style may
|
||||
return the resolved text or the function itself depending on the engine, so read the
|
||||
attribute directly as a fallback: it is in the DOM and always available.
|
||||
- **A `url()`**, meaning the visible thing is an image, and there is no text to recover.
|
||||
- **A counter**, from `counter()` or `counters()`, which is how numbered lists and section
|
||||
numbers are often rendered. The computed value gives you the rendered number.
|
||||
|
||||
```python
|
||||
raw = pseudo_text(page, ".step")
|
||||
if raw and raw.startswith("attr("):
|
||||
attr = raw[len("attr("):-1].strip()
|
||||
raw = page.get_attribute(".step", attr)
|
||||
```
|
||||
|
||||
## Reading many elements at once
|
||||
|
||||
Doing this per element from Python costs a round trip each time. For a list, collect them
|
||||
in one evaluation:
|
||||
|
||||
```python
|
||||
ALL = """
|
||||
(sel) => Array.from(document.querySelectorAll(sel)).map(el => ({
|
||||
text: el.textContent.trim(),
|
||||
before: getComputedStyle(el, '::before').content,
|
||||
after: getComputedStyle(el, '::after').content,
|
||||
}))
|
||||
"""
|
||||
rows = page.evaluate(ALL, ".product-card .label")
|
||||
```
|
||||
|
||||
One evaluation is also one moment in time, which matters on pages where a class is toggled
|
||||
by script and the pseudo-element content changes with it.
|
||||
|
||||
## Where this actually shows up
|
||||
|
||||
Four patterns account for almost all real cases:
|
||||
|
||||
**Status badges.** "New", "Sold out", "Sale" are frequently pure CSS, driven by a class on
|
||||
the parent. The class itself is often the better field to capture, since it is stable while
|
||||
the rendered word is localised.
|
||||
|
||||
**Currency symbols and units.** A price of `19.99` in the DOM with the currency in a
|
||||
`::before` produces a dataset of bare numbers whose currency you cannot recover later. This
|
||||
is the case where the omission does the most damage, because the number looks complete.
|
||||
|
||||
**Required-field markers and icons.** Usually noise, worth recognising so you do not chase
|
||||
them.
|
||||
|
||||
**Row numbering.** Counters render an index that has no DOM representation at all, which
|
||||
matters when the number is the identifier a user would quote.
|
||||
|
||||
## Check for it deliberately, rather than discovering it
|
||||
|
||||
The reliable way to find out whether a page uses this is to ask, once, before writing
|
||||
selectors:
|
||||
|
||||
```python
|
||||
FIND = """
|
||||
() => {
|
||||
const out = [];
|
||||
document.querySelectorAll('*').forEach(el => {
|
||||
for (const p of ['::before', '::after']) {
|
||||
const c = getComputedStyle(el, p).content;
|
||||
if (c && !['none', 'normal', '""'].includes(c) && !c.startsWith('url('))
|
||||
out.push({ tag: el.tagName, cls: el.className, pseudo: p, content: c });
|
||||
}
|
||||
});
|
||||
return out.slice(0, 50);
|
||||
}
|
||||
"""
|
||||
print(page.evaluate(FIND))
|
||||
```
|
||||
|
||||
Run that on one representative page of a new site. It takes a second and tells you whether
|
||||
any visible text is missing from your extraction, which is a question that is otherwise
|
||||
answered weeks later by someone noticing a column of blanks.
|
||||
|
||||
The same class of invisibility appears in two other places worth knowing:
|
||||
[shadow DOM content](how-to-scrape-shadow-dom-playwright.md), which needs a different
|
||||
traversal, and canvas rendering, where there is no text at all and the approach is in
|
||||
[extracting data from canvas charts](how-to-extract-data-from-canvas-charts-playwright.md).
|
||||
|
||||
## A complete extractor that never loses the invisible half
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
CARD = """
|
||||
(sel) => Array.from(document.querySelectorAll(sel)).map(card => {
|
||||
const read = (el) => {
|
||||
if (!el) return null;
|
||||
const before = getComputedStyle(el, '::before').content;
|
||||
const after = getComputedStyle(el, '::after').content;
|
||||
const clean = (c) => (!c || ['none', 'normal', '""'].includes(c) || c.startsWith('url('))
|
||||
? '' : c.replace(/^["']|["']$/g, '');
|
||||
return {
|
||||
dom: el.textContent.trim(),
|
||||
before: clean(before),
|
||||
after: clean(after),
|
||||
classes: el.className,
|
||||
};
|
||||
};
|
||||
return {
|
||||
price: read(card.querySelector('.price')),
|
||||
badge: read(card.querySelector('.badge')),
|
||||
href: card.querySelector('a')?.getAttribute('href') || null,
|
||||
};
|
||||
})
|
||||
"""
|
||||
|
||||
def full_text(part):
|
||||
if not part:
|
||||
return None
|
||||
return (part["before"] + part["dom"] + part["after"]).strip() or None
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("cards.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example.com/category", wait_until="domcontentloaded")
|
||||
page.wait_for_selector(".product-card")
|
||||
|
||||
for card in page.evaluate(CARD, ".product-card"):
|
||||
out.write(json.dumps({
|
||||
"href": card["href"],
|
||||
"price_rendered": full_text(card["price"]), # "€19.99"
|
||||
"price_dom_only": (card["price"] or {}).get("dom"), # "19.99"
|
||||
"badge_rendered": full_text(card["badge"]),
|
||||
"badge_classes": (card["badge"] or {}).get("classes"),
|
||||
"observed_at": time.time(),
|
||||
}, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
```
|
||||
|
||||
Composing `before + dom + after` reproduces what a reader sees, which is the value you
|
||||
usually want. Keeping `price_dom_only` alongside it is the cheap insurance: when the two
|
||||
differ, you know a pseudo-element was carrying something, and when they stop differing after
|
||||
a site update you know the currency symbol moved into the DOM rather than disappearing.
|
||||
|
||||
## The failure mode is silence, not refusal
|
||||
|
||||
Nothing here is a defence, and that is worth stating because it changes how you find it.
|
||||
Pseudo-element content is a styling choice, and no site is hiding a price from you by
|
||||
putting the euro sign in a `::before`. The consequence is that no error, status code or
|
||||
challenge will ever tell you that you missed it.
|
||||
|
||||
That leaves three habits that actually catch it.
|
||||
|
||||
**Probe once per new site**, with the audit snippet above, before writing any selectors.
|
||||
Ten seconds at the start against weeks of a silently wrong column.
|
||||
|
||||
**Compare rendered text against extracted text** on a sample. If the page shows `€19.99`
|
||||
and your row says `19.99`, something is generating the difference, and pseudo-elements are
|
||||
the first suspect:
|
||||
|
||||
```python
|
||||
shown = page.eval_on_selector(".price", "e => e.getBoundingClientRect() && e.innerText")
|
||||
```
|
||||
|
||||
**Prefer the class to the rendered word** for status badges. `badge_classes` survives
|
||||
localisation and copy changes, while the rendered "Sold out" becomes "Ausverkauft" for a
|
||||
German visitor and breaks any filter built on the string.
|
||||
|
||||
If a page genuinely renders text you cannot reach by any of these routes, the remaining
|
||||
possibilities are shadow DOM, canvas, or an image, and each has its own page. What almost
|
||||
never explains it is blocking, which is why this page does not send you to
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md) first: that is
|
||||
the right guide when content is absent, not when it is visible and unreadable.
|
||||
|
||||
## The wider family, and a gap nobody has written down
|
||||
|
||||
Pseudo-element content is the easiest member of a family: text that a person can read and
|
||||
an extractor cannot. The harder member is the shadow DOM, and while researching that side
|
||||
we found something worth stating here, because it changes what you should expect from
|
||||
Playwright.
|
||||
|
||||
Two Playwright issues describe what looks like two separate problems:
|
||||
|
||||
- [#23047](https://github.com/microsoft/playwright/issues/23047) asks for locators to be
|
||||
able to enter `mode: "closed"` shadow roots. Open since May 2023, 26 comments.
|
||||
- [#30816](https://github.com/microsoft/playwright/issues/30816) asks for
|
||||
`Page.content()` to serialize shadow DOM at all, open or closed. Closed, 2 comments.
|
||||
|
||||
They are the same underlying gap seen from two directions: the page's content is not fully
|
||||
reachable through the public API surface. **As of this writing, no third issue or pull
|
||||
request in that repository cites both.** The GitHub search
|
||||
`repo:microsoft/playwright 30816 23047` returns exactly two results, which are the two
|
||||
issues themselves, and #23047 never mentions serialization, `outerHTML`, `getHTML` or
|
||||
snapshots anywhere in its 26 comments.
|
||||
|
||||
That matters practically rather than academically. It means the two symptoms get worked
|
||||
around separately, by people who do not know they are chasing one thing, and it explains
|
||||
why the advice you find for one of them never helps with the other. If your extraction is
|
||||
missing text, check both directions before concluding the page is doing something exotic:
|
||||
a pseudo-element, and a shadow root that neither the locator nor `page.content()` will show
|
||||
you. The traversal for the second is in
|
||||
[scraping shadow DOM content](how-to-scrape-shadow-dom-playwright.md).
|
||||
|
||||
## What to store, and why both forms
|
||||
|
||||
| field | example | why keep it |
|
||||
|---|---|---|
|
||||
| `price_rendered` | `€19.99` | what a person sees |
|
||||
| `price_dom_only` | `19.99` | detects the day the markup changes |
|
||||
| `badge_rendered` | `Sold out` | human readable |
|
||||
| `badge_classes` | `badge badge--soldout` | stable across languages and copy |
|
||||
|
||||
Two columns for one visible string looks redundant and costs almost nothing. It converts a
|
||||
class of silent breakage into a visible one: a diff between the two columns is a fact about
|
||||
the site's markup, and a diff that suddenly disappears across a whole crawl is the earliest
|
||||
warning you will get that the page was redesigned under you.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why does the value come back with quotation marks?** Because `content` is a CSS
|
||||
value and not a string, so it arrives quoted and needs unwrapping. It can also come
|
||||
back as `none`, which means the pseudo-element is not generating anything at all.
|
||||
|
||||
**Can `content` hold something that is not text?** Yes, and each form needs different
|
||||
handling: a counter, an attribute reference, a URL, or a concatenation of several of
|
||||
those. A parser that assumes a plain string quietly mangles all four.
|
||||
|
||||
**Is reading this per element slow?** It costs a round trip each time. For a list,
|
||||
collect the values in a single evaluation in the page and return them together.
|
||||
|
||||
**How do I find out whether a page uses this at all?** Ask once, before writing any
|
||||
selector, instead of discovering it from a column of missing values. Nothing here is a
|
||||
defence, so it fails by silence: the text is simply absent from what an extractor
|
||||
sees.
|
||||
|
||||
**See also:** [How to scrape shadow DOM content with
|
||||
Playwright](how-to-scrape-shadow-dom-playwright.md), [Extract data from canvas charts
|
||||
with Playwright](how-to-extract-data-from-canvas-charts-playwright.md), [How to scrape
|
||||
without getting blocked](how-to-scrape-without-getting-blocked.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- MDN, `Window.getComputedStyle()`,
|
||||
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle - reading a
|
||||
pseudo-element's computed style through the second argument, which is the mechanism
|
||||
this page rests on.
|
||||
- MDN, the `content` property,
|
||||
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/content - the
|
||||
value types the property accepts, checked for the four forms this page separates.
|
||||
@@ -20,7 +20,7 @@ A date-picker looks like a form field and behaves like an application. The value
|
||||
want is not in the DOM waiting to be read: it is behind a grid that shows one month at
|
||||
a time, hides the target date until you page forward to its month, greys out the days
|
||||
you are not allowed to pick, and commits the choice only when you click a rendered day
|
||||
cell rather than typing into the box.
|
||||
cell instead of typing into the box.
|
||||
|
||||
This page is the mechanics of driving one of those with stock Playwright: how to page
|
||||
between months without losing the grid, how to tell an available cell from a disabled
|
||||
@@ -66,7 +66,7 @@ The calendar shows one month. The date you want is some number of months ahead o
|
||||
is currently displayed, so the first job is to read the visible month, compare it to the
|
||||
target, and click the forward control the right number of times.
|
||||
|
||||
Read the header rather than counting clicks blindly, because the picker may open on the
|
||||
Read the header instead of counting clicks blindly, because the picker may open on the
|
||||
current month or on the last month the user touched, and you cannot assume a starting
|
||||
point.
|
||||
|
||||
@@ -134,7 +134,7 @@ def available_day(page, day):
|
||||
|
||||
If `available_day` returns `None`, that is data, not a failure: for an availability
|
||||
scrape, an unpickable day IS the answer for that date. Record it and move to the next
|
||||
one rather than retrying.
|
||||
one instead of retrying.
|
||||
|
||||
## Click to commit, and re-query after every render
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ nav_order: 52
|
||||
To scrape deals and coupon codes with Playwright, drive a real browser that fires a trusted
|
||||
click on each card's reveal button, then capture the code from wherever the click sends it
|
||||
(a new tab, the clipboard, or an XHR response) and read expiry from the card's data
|
||||
attribute rather than the ticking countdown text. A scripted `dispatchEvent` click is
|
||||
attribute instead of the ticking countdown text. A scripted `dispatchEvent` click is
|
||||
untrusted and a reveal guarded by a bot check returns nothing.
|
||||
|
||||
Deal and coupon pages look like the easiest scrape on the web: a grid of cards, each with
|
||||
@@ -69,7 +69,7 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
|
||||
`page.click()` here drives Firefox through its native input path, so the reveal receives
|
||||
an event with `isTrusted` set to true and the correct pointer sequence in front of it. The
|
||||
mouse also arcs to the button on a curve rather than teleporting, which is the difference
|
||||
mouse also arcs to the button on a curve instead of teleporting, which is the difference
|
||||
between a reveal that fires and one that silently no-ops. Nothing about the code below is
|
||||
wrapper-specific API: it is ordinary Playwright, which is the point.
|
||||
|
||||
@@ -173,13 +173,13 @@ def read_expiry(card):
|
||||
return None # only fall back to parsing text if no attribute exists
|
||||
```
|
||||
|
||||
Reading the attribute rather than the rendered text gives you the same value on every run
|
||||
Reading the attribute instead of the rendered text gives you the same value on every run
|
||||
of the same seed, which is what makes a scrape you can diff against yesterday's.
|
||||
|
||||
## Page the grid without a mechanical scroll
|
||||
|
||||
Deal grids scroll infinitely: more cards load as you reach the bottom, and there is no page
|
||||
2 to request. Scroll, wait for the card count to actually grow rather than sleeping a fixed
|
||||
2 to request. Scroll, wait for the card count to actually grow instead of sleeping a fixed
|
||||
interval, and stop when it stops growing.
|
||||
|
||||
```python
|
||||
|
||||
@@ -51,7 +51,7 @@ row = {
|
||||
```
|
||||
|
||||
Those first three fields are part of what the row asserts. Without them, two readings
|
||||
taken an hour apart describe two different questions rather than a change in
|
||||
taken an hour apart describe two different questions instead of a change in
|
||||
availability, and the series you build on top of them measures your own inputs.
|
||||
|
||||
## Read the grid response, not the rendered cells
|
||||
|
||||
@@ -11,7 +11,7 @@ nav_order: 140
|
||||
|
||||
To scrape domain WHOIS records with Playwright, read the record page as labeled
|
||||
key-value lines instead of fixed positions, treat REDACTED FOR PRIVACY as a real
|
||||
value rather than a missing field, keep the raw EPP status code instead of
|
||||
value instead of a missing field, keep the raw EPP status code instead of
|
||||
paraphrasing it, bind creation, expiry and updated dates to their own labels, flag
|
||||
records that describe a privacy proxy instead of the actual registrant, and pace
|
||||
each lookup by whole seconds because the query itself, not the page around it, is
|
||||
@@ -89,7 +89,7 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
```
|
||||
|
||||
Repeated labels, `Domain Status` and `Name Server` almost always appear more than
|
||||
once, collapse into a list rather than overwriting the earlier value. Everything
|
||||
once, collapse into a list instead of overwriting the earlier value. Everything
|
||||
downstream reads from `record` by name, never by an index into the raw text.
|
||||
|
||||
## REDACTED FOR PRIVACY is a value, not a missing field
|
||||
@@ -149,7 +149,7 @@ next. There is no single schema to assume.
|
||||
|
||||
Normalize before doing anything with the values: map the label variants you have
|
||||
actually seen onto a small set of canonical keys, and try each known date format
|
||||
in turn rather than committing to one.
|
||||
in turn instead of committing to one.
|
||||
|
||||
```python
|
||||
from datetime import datetime
|
||||
@@ -204,7 +204,7 @@ def canonical_statuses(record):
|
||||
```
|
||||
|
||||
A domain frequently carries two or three statuses at once, so keep the result as
|
||||
a list rather than collapsing it to a single value.
|
||||
a list instead of collapsing it to a single value.
|
||||
|
||||
## Bind creation, expiry and updated dates to their own labels
|
||||
|
||||
@@ -264,9 +264,9 @@ def scrape_domains(domains, seed=42):
|
||||
return rows
|
||||
```
|
||||
|
||||
Treat a rate-limit response as a hard stop rather than something to retry right
|
||||
Treat a rate-limit response as a hard stop, not something to retry right
|
||||
away. Most lookup services signal it with a specific error string, a blank
|
||||
result, or a captcha page rather than an HTTP error code, and hammering past that
|
||||
result, or a captcha page, not an HTTP error code, and hammering past that
|
||||
signal tends to extend the block instead of working around it.
|
||||
|
||||
## Conclusion
|
||||
@@ -296,7 +296,7 @@ value, distinct from a field the registry's format never includes at all.
|
||||
|
||||
**The registrant email looks like a company, not a person. Why?** The domain
|
||||
likely routes through a privacy or proxy service, and the fields you are reading
|
||||
describe that service, not the actual owner. Flag records like this rather than
|
||||
describe that service, not the actual owner. Flag records like this instead of
|
||||
trusting the contact details at face value.
|
||||
|
||||
**Can I paraphrase a domain status code to make it more readable?** No. EPP
|
||||
|
||||
@@ -63,7 +63,7 @@ There are three places a product number can live, and they are not equally trust
|
||||
## Select the variant and wait for the price XHR
|
||||
|
||||
Playwright gives you the request directly. Wrap the click or the select in
|
||||
`page.expect_response`, and you get the actual offers payload rather than whatever the
|
||||
`page.expect_response`, and you get the actual offers payload, not whatever the
|
||||
DOM happened to show a moment later. The wrapper is a drop-in for stock Playwright, so
|
||||
`browser` below is a real Playwright `Browser` and every method is the one you already
|
||||
know.
|
||||
@@ -93,7 +93,7 @@ DOM node you have to trust. If you would rather subscribe to responses across a
|
||||
session instead of one at a time, [capturing XHR and API responses in Playwright](how-to-capture-xhr-api-responses-playwright.md)
|
||||
covers the listener form.
|
||||
|
||||
If the base price is what you are after and it is painted after load rather than behind
|
||||
If the base price is what you are after and it is painted after load, not behind
|
||||
a variant click, wait for the value to appear instead of guessing at a delay. Blind
|
||||
`sleep` calls are the classic flake here, and [waiting for the page to actually finish
|
||||
loading](how-to-wait-for-page-load-playwright.md) has the specific predicates.
|
||||
@@ -112,7 +112,7 @@ Most storefronts also embed a `application/ld+json` block describing the product
|
||||
search engines. It is a structured, documented format, and it is the cheapest
|
||||
cross-check you have against the number you scraped from the offers XHR. When the two
|
||||
agree you are confident; when they disagree you have learned something real about the
|
||||
page rather than shipping a wrong number silently.
|
||||
page instead of shipping a wrong number silently.
|
||||
|
||||
```python
|
||||
import json
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
---
|
||||
title: "How to scrape energy tariff comparisons with Playwright"
|
||||
description: "Scrape energy tariff comparison sites with Playwright: drive the consumption form that produces the quote, keep standing charge and unit rate apart, and record the assumptions behind every annual figure."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 165
|
||||
---
|
||||
|
||||
|
||||
# How to scrape energy tariff comparisons with Playwright
|
||||
|
||||
To scrape energy tariffs, drive the **consumption form** and record what you entered.
|
||||
These sites do not have prices, they have quotes, and a quote is a function of postcode,
|
||||
annual consumption, meter type and payment method. Two runs with different inputs return
|
||||
different tariffs at different prices, and a row that does not carry its inputs cannot be
|
||||
compared with anything, including itself.
|
||||
|
||||
The second thing to separate is the tariff's two components. A tariff is a standing charge
|
||||
per day plus a unit rate per kilowatt hour, and the headline annual figure is those two
|
||||
combined with an assumed consumption. Store the components; recompute the annual figure
|
||||
when you need it.
|
||||
|
||||
This page covers driving the quote form, keeping the components apart, and recording the
|
||||
assumptions that make a number reproducible.
|
||||
|
||||
## Fill the form the way it expects, in order
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
INPUTS = {
|
||||
"postcode": "BS1 4DJ",
|
||||
"annual_kwh_electricity": 2700,
|
||||
"annual_kwh_gas": 11500,
|
||||
"payment_method": "direct_debit",
|
||||
"meter": "single_rate",
|
||||
}
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example-compare.com/energy")
|
||||
|
||||
page.fill("input[name='postcode']", INPUTS["postcode"])
|
||||
page.click("button#continue")
|
||||
|
||||
page.check("input[value='know_usage']") # reshapes the form
|
||||
page.fill("input[name='elecKwh']", str(INPUTS["annual_kwh_electricity"]))
|
||||
page.fill("input[name='gasKwh']", str(INPUTS["annual_kwh_gas"]))
|
||||
page.select_option("select[name='payment']", INPUTS["payment_method"])
|
||||
page.click("button#showResults")
|
||||
page.wait_for_selector(".tariff-result")
|
||||
```
|
||||
|
||||
The `check` before the fills is the step that catches people. These forms branch on
|
||||
whether you know your usage, and filling consumption fields that are still hidden silently
|
||||
does nothing, so the quote comes back on the site's default assumption instead of yours.
|
||||
This is a multi-step flow, and the ordering discipline is the one in
|
||||
[scraping multi-step wizard flows](how-to-scrape-multi-step-wizard-flow-playwright.md).
|
||||
|
||||
## Keep standing charge and unit rate as separate fields
|
||||
|
||||
```python
|
||||
results = []
|
||||
for card in page.query_selector_all(".tariff-result"):
|
||||
def t(sel):
|
||||
n = card.query_selector(sel)
|
||||
return n.inner_text().strip() if n else None
|
||||
results.append({
|
||||
"supplier": t(".supplier-name"),
|
||||
"tariff": t(".tariff-name"),
|
||||
"unit_rate_text": t(".unit-rate"), # p/kWh
|
||||
"standing_charge_text": t(".standing-charge"), # p/day
|
||||
"annual_estimate_text": t(".annual-cost"),
|
||||
"contract_length": t(".contract-term"),
|
||||
"exit_fee_text": t(".exit-fee"),
|
||||
**{f"input_{k}": v for k, v in INPUTS.items()},
|
||||
})
|
||||
```
|
||||
|
||||
Copying the inputs into every row looks redundant and is the single most valuable thing in
|
||||
the schema. It makes each row self-describing, so a table assembled from ten runs across
|
||||
five postcodes remains analysable a month later, when nobody remembers which run was which.
|
||||
|
||||
A tariff with a low unit rate and a high standing charge beats one with the opposite only
|
||||
above a certain consumption. That crossover is the actual question these datasets can
|
||||
answer, and it is unanswerable from the annual figure alone.
|
||||
|
||||
## Dual fuel, exit fees and the fields that decide the choice
|
||||
|
||||
Three fields change the ranking more than the price does:
|
||||
|
||||
- **Fuel scope.** A dual fuel quote and two single fuel quotes are different products, and
|
||||
comparison sites mix them in one list. Record which each row is.
|
||||
- **Exit fee.** A cheap fixed tariff with a large exit fee is not cheap if rates fall.
|
||||
- **Contract length and end date.** A twelve month fix quoted today ends on a date, and
|
||||
that date is what a rolling comparison has to line up.
|
||||
|
||||
Take them as text and parse later, the same discipline as elsewhere: "None", "£30 per
|
||||
fuel" and "£75" are all common, and only one of them is a number.
|
||||
|
||||
## The quote is a moment, so timestamp it and expect it to move
|
||||
|
||||
```python
|
||||
row["quoted_at"] = time.time()
|
||||
```
|
||||
|
||||
Energy tariffs change frequently and comparison sites cache aggressively. Two runs an hour
|
||||
apart can differ, and a run against a cached result set can return tariffs that are already
|
||||
withdrawn. Where the page shows a validity or a "prices correct as of" line, take it, and
|
||||
prefer it to your own clock when the two disagree.
|
||||
|
||||
## Do not create an account, and do not submit a switch
|
||||
|
||||
Everything above is the public quote engine. These sites also offer to switch you, which
|
||||
requires personal details and creates a real commercial transaction. That boundary is worth
|
||||
stating plainly: reading a quote is scraping, and submitting a switch is entering a
|
||||
contract on behalf of a person.
|
||||
|
||||
Stay on the public side, keep runs to a handful of profiles instead of a sweep of every
|
||||
postcode, and follow the pacing in
|
||||
[rate limiting your own scraper](how-to-scrape-without-getting-blocked.md). A comparison
|
||||
engine runs a real pricing computation per query, so each request costs the operator
|
||||
meaningfully more than serving a page.
|
||||
|
||||
## Store it long, one row per tariff per run
|
||||
|
||||
Append rather than overwrite, with the inputs and timestamps attached, in
|
||||
[JSON Lines](how-to-scrape-to-json-lines-playwright.md) or
|
||||
[a SQLite database](how-to-scrape-into-a-database-playwright.md). The value of this data
|
||||
is entirely in the series: which suppliers moved, when, and how the crossover consumption
|
||||
shifted. A table holding only today's best deal throws away everything that made it worth
|
||||
collecting.
|
||||
|
||||
## A complete run over several consumption profiles
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
PROFILES = [
|
||||
{"postcode": "BS1 4DJ", "elec": 1800, "gas": 7500, "payment": "direct_debit"},
|
||||
{"postcode": "BS1 4DJ", "elec": 2700, "gas": 11500, "payment": "direct_debit"},
|
||||
{"postcode": "BS1 4DJ", "elec": 4200, "gas": 18000, "payment": "direct_debit"},
|
||||
]
|
||||
|
||||
def quote(page, profile):
|
||||
page.goto("https://example-compare.com/energy", wait_until="domcontentloaded")
|
||||
page.fill("input[name='postcode']", profile["postcode"])
|
||||
page.click("button#continue")
|
||||
|
||||
page.check("input[value='know_usage']") # reshapes the form first
|
||||
page.wait_for_selector("input[name='elecKwh']:not([disabled])")
|
||||
page.fill("input[name='elecKwh']", str(profile["elec"]))
|
||||
page.fill("input[name='gasKwh']", str(profile["gas"]))
|
||||
page.select_option("select[name='payment']", profile["payment"])
|
||||
page.click("button#showResults")
|
||||
page.wait_for_selector(".tariff-result, .no-tariffs", timeout=40000)
|
||||
|
||||
if page.query_selector(".no-tariffs"):
|
||||
return [{"result": "no_tariffs", **{f"input_{k}": v for k, v in profile.items()}}]
|
||||
|
||||
validity = page.query_selector(".prices-correct-as-of")
|
||||
return [{
|
||||
**row,
|
||||
"prices_as_of": validity.inner_text().strip() if validity else None,
|
||||
**{f"input_{k}": v for k, v in profile.items()},
|
||||
} for row in read_results(page)]
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("tariffs.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
for profile in PROFILES:
|
||||
for row in quote(page, profile):
|
||||
row["quoted_at"] = time.time()
|
||||
out.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(8000)
|
||||
```
|
||||
|
||||
Three consumption profiles rather than one is what makes the dataset answer the question
|
||||
that matters. The cheapest tariff at 1,800 kWh is frequently not the cheapest at 4,200,
|
||||
and that crossover is invisible from a single quote no matter how often you repeat it.
|
||||
|
||||
The wait for `input[name='elecKwh']:not([disabled])` is the guard on the branch: it fails
|
||||
loudly if the form did not reshape, instead of quietly filling a hidden field and taking
|
||||
the site's default assumption.
|
||||
|
||||
## A pricing engine is an expensive request, and behaves like one
|
||||
|
||||
Comparison sites differ from most scraping targets in that each query runs a real
|
||||
computation against supplier tariffs. Three consequences.
|
||||
|
||||
**Slow is normal, and a timeout is not a block.** Forty seconds for a result set is
|
||||
ordinary at peak. Treat a timeout as a retry candidate rather than as a refusal, using the
|
||||
backoff shape in
|
||||
[retrying failed requests](how-to-retry-failed-requests-playwright.md).
|
||||
|
||||
**Cached result sets serve withdrawn tariffs.** The engine may return a set computed
|
||||
minutes ago, which is why `prices_as_of` is captured whenever the site prints it. Where two
|
||||
runs an hour apart return identical results with the same stamp, you read a cache twice
|
||||
rather than confirming stability.
|
||||
|
||||
**Volume is what draws attention, not identity.** A handful of profiles a day is
|
||||
indistinguishable from a household comparing options. A sweep of every postcode is a
|
||||
different traffic shape entirely and is the one thing guaranteed to end the access. That is
|
||||
a limit worth writing into the script rather than remembering, and the general argument is
|
||||
in [rate limiting your own scraper](how-to-rate-limit-your-scraper-playwright.md).
|
||||
|
||||
## The schema, and the crossover query it exists for
|
||||
|
||||
One row per tariff per profile per run:
|
||||
|
||||
| field | why |
|
||||
|---|---|
|
||||
| `unit_rate_text`, `standing_charge_text` | the two components, unparsed |
|
||||
| `annual_estimate_text` | the site's own arithmetic, kept for comparison |
|
||||
| `input_elec`, `input_gas`, `input_postcode`, `input_payment` | the query, copied down |
|
||||
| `contract_length`, `exit_fee_text` | what decides the ranking beyond price |
|
||||
| `prices_as_of`, `quoted_at` | their clock and yours |
|
||||
|
||||
With the components and several profiles, the crossover falls out as arithmetic rather
|
||||
than another scrape: for two tariffs, the consumption at which their annual costs are equal
|
||||
is the difference in standing charges divided by the difference in unit rates. That number
|
||||
is the actual advice a household needs, it is not published anywhere, and it is
|
||||
unreachable from the annual estimate the site puts in large type.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why does the quote form reject my inputs?** Usually order. These forms branch on
|
||||
whether you know your consumption, and the fields that appear depend on that answer,
|
||||
so filling them in the wrong sequence leaves a control the engine still expects.
|
||||
|
||||
**Should I store one price per tariff?** No. A standing charge and a unit rate are
|
||||
separate numbers and the ranking between two tariffs flips depending on consumption.
|
||||
Keep them apart, and copy the inputs into every row even though it looks redundant.
|
||||
|
||||
**Two runs an hour apart disagree. Which is right?** Both. A quote is a moment:
|
||||
tariffs change often and comparison sites cache aggressively, so the run timestamp
|
||||
belongs in the row and a disagreement is data about the market.
|
||||
|
||||
**Can I follow the switch flow to get more detail?** No. Everything here is the public
|
||||
quote engine. A switch requires personal details and creates a real commercial action,
|
||||
which is a different activity entirely.
|
||||
|
||||
**See also:** [Scrape a multi-step wizard flow with
|
||||
Playwright](how-to-scrape-multi-step-wizard-flow-playwright.md), [How to retry failed
|
||||
requests when scraping Playwright](how-to-retry-failed-requests-playwright.md), [How
|
||||
to scrape to JSON Lines with Playwright](how-to-scrape-to-json-lines-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Input, https://playwright.dev/python/docs/input - `check()` and
|
||||
`fill()`, checked for driving a branching form in the order the engine expects.
|
||||
- This project's page on multi-step wizard flows, which carries the general shape this
|
||||
page applies to a pricing engine.
|
||||
@@ -0,0 +1,293 @@
|
||||
---
|
||||
title: "How to scrape EV charging availability with Playwright"
|
||||
description: "Scrape EV charger availability with Playwright: capture the live status feed the map is drawing from, record a timestamp with every reading, and treat availability as a measurement instead of a fact."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 151
|
||||
---
|
||||
|
||||
|
||||
# How to scrape EV charging availability with Playwright
|
||||
|
||||
To scrape charger availability, capture the **status feed** the map is drawing from,
|
||||
not the map, and stamp every reading with the time you took it. Availability is
|
||||
not an attribute of a charging point. It is a measurement that was true for a few
|
||||
seconds, and a row without a timestamp is a claim you cannot check later.
|
||||
|
||||
This is what separates charger data from most listing data. A restaurant menu scraped
|
||||
yesterday is still roughly the menu. A connector that read "available" ninety seconds
|
||||
ago tells you almost nothing, and a database of such rows without times is not a dataset,
|
||||
it is a pile of expired assertions.
|
||||
|
||||
This page covers finding the feed behind the map, modelling a charging point correctly
|
||||
as a site with several connectors, and polling at a rate that is honest about both the
|
||||
data and the operator's servers.
|
||||
|
||||
## Read the feed, not the pins
|
||||
|
||||
Charger maps are drawn from a JSON response, and the pins are a rendering of it. Capture
|
||||
the response instead of parsing markers out of the canvas or the marker layer:
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
payloads = []
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
|
||||
def on_response(response):
|
||||
if "/api/" in response.url and "station" in response.url.lower():
|
||||
try:
|
||||
payloads.append({
|
||||
"at": time.time(),
|
||||
"url": response.url,
|
||||
"body": response.json(),
|
||||
})
|
||||
except Exception:
|
||||
pass # not JSON: a tile, a sprite, an analytics beacon
|
||||
|
||||
page.on("response", on_response)
|
||||
page.goto("https://example.com/map")
|
||||
page.wait_for_timeout(4000) # let the map settle and issue its queries
|
||||
```
|
||||
|
||||
The map usually re-queries as you pan, with a bounding box in the request. That is the
|
||||
handle you want: it lets you walk a region deliberately instead of scrolling a map and
|
||||
hoping. The mechanics of capturing these responses, including the ordering problems, are
|
||||
in [capturing XHR and API responses](how-to-capture-xhr-api-responses-playwright.md).
|
||||
|
||||
## A charging point is not one thing
|
||||
|
||||
The single most common modelling error here is treating a pin as a charger. A pin is a
|
||||
site. A site has several charging points. A point has several connectors, often of
|
||||
different types and speeds, and availability lives at the connector level:
|
||||
|
||||
```python
|
||||
def flatten(station):
|
||||
site = {"site_id": station["id"], "name": station.get("name")}
|
||||
for point in station.get("evses", []):
|
||||
for connector in point.get("connectors", []):
|
||||
yield {
|
||||
**site,
|
||||
"point_id": point.get("uid"),
|
||||
"connector_id": connector.get("id"),
|
||||
"standard": connector.get("standard"), # CCS, CHAdeMO, Type 2
|
||||
"power_kw": connector.get("max_electric_power", 0) / 1000 or None,
|
||||
"status": point.get("status"), # AVAILABLE, CHARGING, OUTOFORDER
|
||||
}
|
||||
```
|
||||
|
||||
Flattening to one row per connector costs nothing and makes every later question
|
||||
answerable. Flattening to one row per site makes "is there a fast charger free" a
|
||||
question your data cannot answer, and you will not notice until someone asks it.
|
||||
|
||||
## Stamp the time, and keep the operator's own timestamp separately
|
||||
|
||||
Two times matter and they are not the same. There is when **you** read the value, and
|
||||
there is when the **operator** last heard from the hardware. The second is often in the
|
||||
payload as `last_updated`, and it is frequently minutes or hours old:
|
||||
|
||||
```python
|
||||
row["observed_at"] = payloads[-1]["at"] # when we looked
|
||||
row["reported_at"] = station.get("last_updated") # when the network last knew
|
||||
```
|
||||
|
||||
Keep both. A connector reported as available with a `last_updated` from six hours ago is
|
||||
a different fact from one updated forty seconds ago, and collapsing them into a single
|
||||
"available" is how a dataset becomes confidently wrong. When the operator gives you no
|
||||
`last_updated` at all, record that absence instead of substituting your own time.
|
||||
|
||||
## Poll on the data's clock, not on yours
|
||||
|
||||
Status changes on the scale of a charging session. Polling every ten seconds produces
|
||||
almost entirely duplicate rows and an obvious traffic pattern; polling once an hour
|
||||
misses most sessions. A few minutes is the honest middle, and storing only changes keeps
|
||||
the volume sane:
|
||||
|
||||
```python
|
||||
last = {}
|
||||
|
||||
def changed(row):
|
||||
key = (row["site_id"], row["connector_id"])
|
||||
if last.get(key) == row["status"]:
|
||||
return False
|
||||
last[key] = row["status"]
|
||||
return True
|
||||
```
|
||||
|
||||
Write the transitions in place of the polls. The result is a state history you can
|
||||
replay, at a fraction of the rows, and it survives a gap in collection better than a
|
||||
dense series with holes in it.
|
||||
|
||||
Pace the loop deliberately. The rules and the reasoning are in
|
||||
[rate limiting your own scraper](how-to-rate-limit-your-scraper-playwright.md), and they
|
||||
matter more here than on a static site: a poll loop is by definition repetitive traffic,
|
||||
which is the easiest kind to notice.
|
||||
|
||||
## Two traps specific to this data
|
||||
|
||||
**The map filters before it queries.** Most of these interfaces default to hiding
|
||||
out-of-service points, or to showing only connector types matched to a vehicle the site
|
||||
remembers. The feed then arrives pre-filtered and looks complete. Check the request
|
||||
parameters for a filter you did not set, and clear it in the interface rather than in the
|
||||
URL, so the site's own state matches what you asked for.
|
||||
|
||||
**Coverage is bounded by the viewport.** The query carries a bounding box, and a large
|
||||
box is often silently capped at a maximum number of results. Walk a grid of small boxes
|
||||
instead of one large one, and check for a `truncated` or `total` field that tells you the
|
||||
response was cut.
|
||||
|
||||
## What this is good for, and what it is not
|
||||
|
||||
Charger availability is a live operational signal. It supports questions about
|
||||
utilisation, reliability and which sites are chronically full. It does not support a
|
||||
claim about what is free right now, unless the reading is seconds old, because by the time
|
||||
a row lands in a database it may already be wrong.
|
||||
|
||||
If you keep the connector-level rows with both timestamps, that limitation is visible in
|
||||
the data itself, which is the point. Store it in something you can query by time, such as
|
||||
[a SQLite database written as you go](how-to-scrape-into-a-database-playwright.md), and
|
||||
resist the temptation to keep only the latest value per connector.
|
||||
|
||||
## A complete poller, with the bounding box walked deliberately
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
BOXES = [ # small boxes beat one big one: see the cap below
|
||||
(51.44, -2.62, 51.47, -2.56),
|
||||
(51.47, -2.62, 51.50, -2.56),
|
||||
]
|
||||
|
||||
def harvest(page, box):
|
||||
south, west, north, east = box
|
||||
captured = []
|
||||
|
||||
def on_response(response):
|
||||
if "station" in response.url.lower() and "/api/" in response.url:
|
||||
try:
|
||||
captured.append(response.json())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
page.on("response", on_response)
|
||||
page.goto(f"https://example.com/map?sw={south},{west}&ne={north},{east}")
|
||||
page.wait_for_timeout(4000)
|
||||
page.remove_listener("response", on_response)
|
||||
return captured
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("chargers.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
while True:
|
||||
for box in BOXES:
|
||||
for payload in harvest(page, box):
|
||||
stations = payload.get("stations") or payload.get("data") or []
|
||||
if payload.get("truncated") or len(stations) >= 500:
|
||||
print("box capped, split it:", box)
|
||||
for station in stations:
|
||||
for row in flatten(station):
|
||||
row["observed_at"] = time.time()
|
||||
out.write(json.dumps(row) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(2000)
|
||||
time.sleep(300)
|
||||
```
|
||||
|
||||
Removing the listener at the end of each box matters more than it looks. Leaving it
|
||||
attached across boxes means responses from the previous query keep arriving into the next
|
||||
box's bucket, and you attribute chargers to a region they are not in. That ordering trap,
|
||||
and the related one where the response lands before you attach, are covered in
|
||||
[capturing XHR and API responses](how-to-capture-xhr-api-responses-playwright.md).
|
||||
|
||||
The explicit cap check is there because a silently truncated response is the standard way
|
||||
these maps limit load. A box that returns exactly 500 stations is almost never a box that
|
||||
contains exactly 500 stations.
|
||||
|
||||
## What a charging network sees, and why a poll is the hard case
|
||||
|
||||
Most listing sites see a scraper once. A charger poller comes back every few minutes,
|
||||
forever, from the same session, asking for the same regions. That is the traffic shape
|
||||
that is easiest to identify, and no amount of fingerprint work makes a fixed-interval
|
||||
loop look like a person watching a map.
|
||||
|
||||
Two things genuinely help, and they are about behaviour rather than identity.
|
||||
|
||||
Vary the interval rather than sleeping a constant. A jittered wait around a target rate
|
||||
keeps the average where you want it without producing a metronome:
|
||||
|
||||
```python
|
||||
import random
|
||||
time.sleep(300 + random.uniform(-45, 45))
|
||||
```
|
||||
|
||||
Read only what changed. If the operator's payload carries a `last_updated`, skip stations
|
||||
whose value has not moved rather than re-querying their detail:
|
||||
|
||||
```python
|
||||
if station.get("last_updated") == seen.get(station["id"]):
|
||||
continue
|
||||
```
|
||||
|
||||
Underneath that, the browser still has to look like a browser, because these APIs are
|
||||
usually behind the same edge protection as the site. A patched Firefox driven by stock
|
||||
Playwright gets the JSON that a stripped client is refused, and the reasoning and debug
|
||||
order live in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## The schema that makes utilisation answerable
|
||||
|
||||
The reason to keep connector-level transitions rather than snapshots is that it makes the
|
||||
useful questions cheap:
|
||||
|
||||
| question | what it needs |
|
||||
|---|---|
|
||||
| how often is this site full | transitions per connector, ordered |
|
||||
| which connectors are broken for weeks | a long run of `OUTOFORDER` with no change |
|
||||
| when is demand highest | transitions bucketed by hour of day |
|
||||
| is the operator's data stale | the gap between `reported_at` and `observed_at` |
|
||||
|
||||
None of those are answerable from a table holding the current status per connector, which
|
||||
is the shape almost every first attempt produces. One row per state change, with
|
||||
`site_id`, `point_id`, `connector_id`, `standard`, `power_kw`, `status`, `observed_at`,
|
||||
`reported_at`, answers all four.
|
||||
|
||||
Write it as [JSON Lines](how-to-scrape-to-json-lines-playwright.md) while collecting and
|
||||
load it into a database for querying. Appending is what makes an interrupted poll leave
|
||||
usable data instead of a hole, and a poll that runs for weeks will be interrupted.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Should I read the map pins or the network request behind them?** The request.
|
||||
Charger maps draw their pins from a JSON response, and the pins are a rendering of it
|
||||
that has already lost fields. Capture the response and you get the operator's own
|
||||
model, including the parts the map does not draw.
|
||||
|
||||
**Why is my charger count wrong?** Almost always because a pin was treated as a
|
||||
charger. A pin is a site, a site holds several charging points, and a point holds
|
||||
several connectors. Availability lives at the connector, so a count taken at the pin
|
||||
level answers a different question.
|
||||
|
||||
**How often should I poll charger status?** On the data's clock, not yours. Status
|
||||
changes on the scale of a charging session, so a ten-second poll produces almost
|
||||
entirely duplicate rows and looks like exactly what it is: a script that never sleeps.
|
||||
|
||||
**Which timestamp should I store?** Both. When you read the value and when the
|
||||
operator says the value was true are different facts, and only the second one lets you
|
||||
tell a stale feed from a busy charger.
|
||||
|
||||
**See also:** [How to capture XHR and API responses in
|
||||
Playwright](how-to-capture-xhr-api-responses-playwright.md), [How to rate limit your
|
||||
own Playwright scraper](how-to-rate-limit-your-scraper-playwright.md), [How to scrape
|
||||
into a SQLite database with Playwright](how-to-scrape-into-a-database-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Network, https://playwright.dev/python/docs/network -
|
||||
`page.expect_response()` and `page.route()`, checked for the response-capture
|
||||
pattern this page uses and for attaching and detaching a listener around a single
|
||||
query.
|
||||
- This project's page on capturing XHR and API responses, which covers the general
|
||||
form that this page applies to a live availability feed.
|
||||
@@ -12,7 +12,7 @@ nav_order: 42
|
||||
To scrape event and ticket listings with Playwright, wait for the availability request
|
||||
instead of the initial HTML, attach each event's declared source timezone and store UTC
|
||||
alongside it, step the calendar widget to reach future dates, and poll the state attribute
|
||||
rather than the visible label. The one thing that decides whether any of it runs is that
|
||||
instead of the visible label. The one thing that decides whether any of it runs is that
|
||||
the browser's timezone matches the proxy's exit IP.
|
||||
|
||||
| What trips up an event scraper | The fix |
|
||||
|
||||
@@ -10,7 +10,7 @@ nav_order: 108
|
||||
# How to scrape currency exchange rates with Playwright
|
||||
|
||||
**To scrape currency exchange rates with Playwright, capture the quote response the
|
||||
widget already fetches rather than reading the number it paints, and write a row
|
||||
widget already fetches instead of reading the number it paints, and write a row
|
||||
carrying the base code, the quote code, the side, the amount and a UTC arrival
|
||||
timestamp, because a bare "1.08" names one currency out of two, states no direction and
|
||||
hides which side of the spread produced it.**
|
||||
@@ -184,7 +184,7 @@ store because it is easiest to reach.
|
||||
|
||||
The three that matter are ordered. The feed's own `quoted_utc` is when the price was
|
||||
made, and it is the only one that belongs on a time axis. The HTTP `Date` header is the
|
||||
server clock at response time, at one second of resolution, so it brackets rather than
|
||||
server clock at response time, at one second of resolution, so it brackets, not
|
||||
measures. Your arrival stamp is when the bytes reached the browser, and it is the only
|
||||
one you can always produce.
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ nav_order: 135
|
||||
# How to scrape museum and gallery exhibition dates with Playwright
|
||||
|
||||
To scrape museum and gallery exhibition dates with Playwright, read the run as a range
|
||||
rather than a point: pull `startDate` and `endDate` from the page's own Event node instead
|
||||
instead of a point: pull `startDate` and `endDate` from the page's own Event node instead
|
||||
of a single displayed date, key each run by the pair of exhibition and venue so a touring
|
||||
show does not collapse into one row, store a last-checked timestamp so a moved close date
|
||||
reads as an extension instead of an error, and keep a timed-entry booking widget's slot
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
---
|
||||
title: "How to scrape ferry schedules with Playwright"
|
||||
description: "Scrape ferry timetables with Playwright: query by date because sailings are seasonal, keep the route direction as part of the key, and record cancellations as data, not as missing rows."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 153
|
||||
---
|
||||
|
||||
|
||||
# How to scrape ferry schedules with Playwright
|
||||
|
||||
To scrape a ferry timetable, query it **date by date** instead of pulling a published
|
||||
schedule page, keep the direction in the key, and treat a sailing that disappears as an
|
||||
event, not as an absence. Ferry schedules are seasonal, weather-dependent and
|
||||
frequently amended, which makes them one of the few timetable types where yesterday's
|
||||
capture genuinely does not describe today.
|
||||
|
||||
The trap is that these operators also publish a tidy PDF or HTML timetable for the
|
||||
season, and it is very tempting to parse that once and be done. That document is the
|
||||
plan. The booking engine is the truth, and on any given day the two disagree.
|
||||
|
||||
This page covers driving the date-based query, modelling a sailing so that two
|
||||
directions do not collapse into one, and recording the amendments that make the data
|
||||
worth having.
|
||||
|
||||
## Query by date, because the season decides the timetable
|
||||
|
||||
Drive the operator's own date control and step through the range you need:
|
||||
|
||||
```python
|
||||
from datetime import date, timedelta
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
def sailings_for(page, route, day):
|
||||
page.goto(f"https://example.com/timetable?route={route}")
|
||||
page.fill("input[name='date']", day.isoformat())
|
||||
page.click("button[type='submit']")
|
||||
page.wait_for_selector(".sailing, .no-sailings")
|
||||
if page.query_selector(".no-sailings"):
|
||||
return []
|
||||
out = []
|
||||
for row in page.query_selector_all(".sailing"):
|
||||
out.append({
|
||||
"date": day.isoformat(),
|
||||
"depart": row.query_selector(".depart-time").inner_text().strip(),
|
||||
"arrive": row.query_selector(".arrive-time").inner_text().strip(),
|
||||
"vessel": (row.query_selector(".vessel") or row).inner_text().strip(),
|
||||
})
|
||||
return out
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
day = date.today()
|
||||
for offset in range(0, 60):
|
||||
rows = sailings_for(page, "north-crossing", day + timedelta(days=offset))
|
||||
```
|
||||
|
||||
The explicit `.no-sailings` branch is the part people leave out. A day with no service
|
||||
and a day where the selector silently failed produce the same empty list, and once that
|
||||
distinction is lost the dataset quietly grows holes that look like winter.
|
||||
|
||||
## Direction is part of the identity, not a field you can add later
|
||||
|
||||
A route has two directions and the operator often shows them on the same page, sometimes
|
||||
in two tables, sometimes in one table with a column. A sailing keyed on
|
||||
`(route, date, departure time)` will collide across directions, and the collision is
|
||||
silent because both rows look plausible:
|
||||
|
||||
```python
|
||||
"from_port": header_port(row, "from"),
|
||||
"to_port": header_port(row, "to"),
|
||||
```
|
||||
|
||||
Capture the two ports per row, even when the page groups them under a heading. If the
|
||||
page really does put direction only in a heading, read the heading into every row
|
||||
underneath it rather than trusting yourself to remember the grouping later:
|
||||
|
||||
```python
|
||||
current_direction = None
|
||||
for node in page.query_selector_all(".timetable h3, .timetable .sailing"):
|
||||
cls = node.get_attribute("class") or ""
|
||||
if node.evaluate("e => e.tagName") == "H3":
|
||||
current_direction = node.inner_text().strip()
|
||||
continue
|
||||
row = read_sailing(node)
|
||||
row["direction"] = current_direction
|
||||
```
|
||||
|
||||
## Cancellations and amendments are the interesting data
|
||||
|
||||
Operators publish disruption separately from the timetable, usually as a notice banner or
|
||||
a status column. That is the part that a seasonal PDF can never give you:
|
||||
|
||||
```python
|
||||
notices = [n.inner_text().strip()
|
||||
for n in page.query_selector_all(".service-notice, .disruption")]
|
||||
for row in rows:
|
||||
status_cell = row_node.query_selector(".status")
|
||||
row["status"] = status_cell.inner_text().strip() if status_cell else "scheduled"
|
||||
```
|
||||
|
||||
Store the status per sailing and the notices per query. When a sailing vanishes between
|
||||
two captures of the same date, write that transition explicitly rather than deleting the
|
||||
row: a schedule dataset whose history is overwritten cannot answer the one question it is
|
||||
uniquely able to answer, which is how often this crossing actually runs.
|
||||
|
||||
## Two mechanical traps on these sites
|
||||
|
||||
**The date field is a picker, not an input.** Many operators use a calendar widget that
|
||||
ignores a written value and only commits on a click. If `fill` leaves the results
|
||||
unchanged, open the picker and click the day, which is the same problem described in
|
||||
[scraping date-picker calendars](how-to-scrape-date-picker-calendar-playwright.md).
|
||||
|
||||
**Results load into the page without a navigation.** The submit button triggers a request
|
||||
and swaps a region. Waiting for a load event returns immediately and you read the previous
|
||||
day's table. Wait for the result region to change, or capture the response directly with
|
||||
the technique in
|
||||
[capturing XHR and API responses](how-to-capture-xhr-api-responses-playwright.md).
|
||||
|
||||
## Pace it like the resource it is
|
||||
|
||||
Sixty days across a handful of routes is a few hundred queries, which is fine once a day
|
||||
and rude every hour. Timetables change on the scale of a season, with same-day amendments
|
||||
layered on top, so a daily full sweep plus a short poll of the current day covers the real
|
||||
volatility. The pacing rules are in
|
||||
[rate limiting your own scraper](how-to-rate-limit-your-scraper-playwright.md).
|
||||
|
||||
Ferry operators are also small sites with real seasonal traffic spikes. Running the sweep
|
||||
overnight in the operator's own timezone is a courtesy that costs you nothing and keeps
|
||||
the run out of the window where it would actually be felt.
|
||||
|
||||
## A complete sweep, resumable by construction
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from datetime import date, timedelta
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
ROUTES = ["north-crossing", "island-hop"]
|
||||
HORIZON = 60
|
||||
|
||||
def already_done(path):
|
||||
seen = set()
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
r = json.loads(line)
|
||||
seen.add((r["route"], r["date"]))
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
return seen
|
||||
|
||||
path = "sailings.jsonl"
|
||||
done = already_done(path)
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open(path, "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
for route in ROUTES:
|
||||
for offset in range(HORIZON):
|
||||
day = date.today() + timedelta(days=offset)
|
||||
if (route, day.isoformat()) in done:
|
||||
continue
|
||||
rows = sailings_for(page, route, day)
|
||||
out.write(json.dumps({
|
||||
"route": route,
|
||||
"date": day.isoformat(),
|
||||
"observed_at": time.time(),
|
||||
"sailings": rows,
|
||||
"notices": [n.inner_text().strip()
|
||||
for n in page.query_selector_all(".service-notice, .disruption")],
|
||||
}, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(2500)
|
||||
```
|
||||
|
||||
Reading back what is already on disk is a cheaper resume than a checkpoint file, because
|
||||
it cannot drift out of sync with the data it describes. Note that the record is written
|
||||
even when `sailings` is empty: a day with no service is a fact, and skipping the write
|
||||
would make it indistinguishable from a day the sweep never reached. The longer form of
|
||||
that argument is in
|
||||
[resuming an interrupted scrape](how-to-resume-an-interrupted-scrape-playwright.md).
|
||||
|
||||
## Booking engines defend harder than timetable pages
|
||||
|
||||
A ferry timetable lives inside a booking engine, and booking engines are protected because
|
||||
they are a target for inventory scraping and card testing. That shapes what works.
|
||||
|
||||
**The date query is a real search, not a page view.** Each submission runs an availability
|
||||
lookup against live inventory, which is expensive for the operator and is exactly the
|
||||
request that gets rate limited first. Sixty days across two routes is 120 lookups, which
|
||||
is fine overnight and rude in a tight loop.
|
||||
|
||||
**Refusal is often silent.** Rather than an error, you get the shell with an empty result
|
||||
region, which parses as a day with no sailings. That failure writes plausible rows and is
|
||||
never noticed, so guard on the positive marker:
|
||||
|
||||
```python
|
||||
page.wait_for_selector(".sailing, .no-sailings", timeout=20000)
|
||||
if not page.query_selector(".sailing") and not page.query_selector(".no-sailings"):
|
||||
raise RuntimeError("neither sailings nor a no-service marker: failed read")
|
||||
```
|
||||
|
||||
**A real browser is the price of entry.** These engines fingerprint aggressively and a
|
||||
stripped client usually never reaches the timetable. Driving stock Playwright against a
|
||||
patched Firefox is what makes the query look like the query a passenger makes; the debug
|
||||
order when it stops working is in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## The schema that answers "does this crossing actually run"
|
||||
|
||||
Keep sailings nested under a query record rather than flattened into one table, or flatten
|
||||
with the query context copied down. Either way these five fields are what make the dataset
|
||||
worth having:
|
||||
|
||||
| field | why |
|
||||
|---|---|
|
||||
| `route` and `direction` | two directions collide on time alone |
|
||||
| `date` | the query date, not the date you ran |
|
||||
| `status` | scheduled, cancelled, full, at the sailing level |
|
||||
| `observed_at` | the same date read twice tells you when it changed |
|
||||
| `notices` | the disruption text, per query, verbatim |
|
||||
|
||||
The interesting analysis is the difference between two captures of the same date. A
|
||||
sailing that was scheduled on Monday and gone by Thursday is a cancellation, and that is
|
||||
the number a seasonal PDF can never give you: not what the operator plans to run, but what
|
||||
the operator actually ran. Storing every capture rather than updating in place is what
|
||||
makes that question answerable at all.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why does the same route return a different timetable on different days?** Because
|
||||
the season decides the timetable. Ferry operators publish per-date, not a single
|
||||
annual grid, so a query without an explicit date returns whatever the site thinks
|
||||
today is and a series built that way silently mixes seasons.
|
||||
|
||||
**Do I need to scrape each direction separately?** Direction is part of a sailing's
|
||||
identity, not a column you can add afterwards. Operators often show both directions on
|
||||
one page, sometimes in two tables and sometimes in one with a toggle, so decide which
|
||||
you are reading before you store a row.
|
||||
|
||||
**The date field ignores what I type. What now?** It is a calendar widget, not a text
|
||||
input. Open it and click the day, the way a person does. A written value leaves the
|
||||
widget's internal state unchanged and the search runs against the previous date.
|
||||
|
||||
**Where do cancellations show up?** Separately from the timetable, usually as a notice
|
||||
banner or a status column, and they are the most interesting part of the data. A
|
||||
timetable without the disruption record describes an intention, not a service.
|
||||
|
||||
**See also:** [Scrape date-picker calendars with
|
||||
Playwright](how-to-scrape-date-picker-calendar-playwright.md), [How to resume an
|
||||
interrupted scrape with
|
||||
Playwright](how-to-resume-an-interrupted-scrape-playwright.md), [How to rate limit
|
||||
your own Playwright scraper](how-to-rate-limit-your-scraper-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Input, https://playwright.dev/python/docs/input - `locator.fill()`,
|
||||
which focuses the element and fires an input event, against `press_sequentially()`,
|
||||
which types character by character with an optional delay. Checked for why a written
|
||||
date does not commit in a calendar widget.
|
||||
- This project's page on driving date pickers and calendar widgets, which this page
|
||||
relies on instead of restating.
|
||||
@@ -9,8 +9,8 @@ nav_order: 30
|
||||
|
||||
# How to scrape flight prices with Playwright
|
||||
|
||||
To scrape flight prices with Playwright, wait for the search to report itself complete
|
||||
rather than for the page to load or the network to go idle, then read the settled fare
|
||||
To scrape flight prices with Playwright, wait for the search to report itself complete,
|
||||
not for the page to load or the network to go idle, then read the settled fare
|
||||
matrix in one pass. Because a fare scan is many searches, run every one of them as the
|
||||
same seeded browser, so the endpoint feeding the fares sees one consistent device rather
|
||||
than a new machine each time.
|
||||
@@ -20,7 +20,7 @@ submit an origin, a destination and a pair of dates, the navigation settles, and
|
||||
page is empty. Nothing you wanted is in the DOM yet. The fares are still arriving.
|
||||
|
||||
This page is about that gap: why the results stream in after the page has finished
|
||||
loading, how to detect the moment they are actually complete rather than the moment the
|
||||
loading, how to detect the moment they are actually complete, not the moment the
|
||||
network went briefly quiet, and how to run a whole scan of dates without every search
|
||||
looking like a different device to the endpoint that is feeding you the fares.
|
||||
|
||||
@@ -59,7 +59,7 @@ The reliable approach is to watch the responses the search itself produces and w
|
||||
the one that says it is finished. Capturing those responses is the same technique used
|
||||
for any streamed API, covered in
|
||||
[how to capture XHR and API responses](how-to-capture-xhr-api-responses-playwright.md);
|
||||
here you use it to find the terminal message rather than to read the data.
|
||||
here you use it to find the terminal message, not to read the data.
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
@@ -149,7 +149,7 @@ as waiting on load, one layer up.
|
||||
## Running a whole fare scan without looking like a new device each time
|
||||
|
||||
Pin one seed for the entire scan and every search derives the same browser identity, so
|
||||
the whole run looks like one consistent device rather than a new machine on each request.
|
||||
the whole run looks like one consistent device in place of a new machine on each request.
|
||||
A single search is rarely the goal: you want a fortnight of departure dates, or the same
|
||||
route priced every morning, which is dozens or hundreds of searches. This is where the
|
||||
browser you run the scan with starts to matter as much as the waits.
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
---
|
||||
title: "How to scrape flight status boards with Playwright"
|
||||
description: "Scrape airport arrival and departure boards with Playwright: read a board that rewrites itself, keep scheduled and estimated times as separate fields, and key rows on the flight and the day."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 156
|
||||
---
|
||||
|
||||
|
||||
# How to scrape flight status boards with Playwright
|
||||
|
||||
To scrape an arrivals or departures board, capture the row while the board is **between
|
||||
refreshes**, and keep scheduled time and estimated time as two separate fields. These
|
||||
boards rewrite their own DOM every thirty to sixty seconds, wholesale, and a scraper that
|
||||
iterates over rows while a refresh lands reads half of the old table and half of the new
|
||||
one without any error.
|
||||
|
||||
The second half of the problem is modelling. A flight is not identified by its number.
|
||||
The same number flies every day, and on a delayed day it appears on two calendar days at
|
||||
once, so a row keyed on flight number alone overwrites yesterday with today.
|
||||
|
||||
This page covers reading a self-refreshing board safely, keeping the two times apart, and
|
||||
keying rows so a delay does not eat history.
|
||||
|
||||
## Snapshot the table in one evaluation
|
||||
|
||||
Do not iterate the DOM row by row from Python. Each call crosses into the page separately,
|
||||
and the board can replace the table between two of them. Take the whole table in a single
|
||||
evaluation instead:
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
READ_BOARD = """
|
||||
() => Array.from(document.querySelectorAll('table.board tbody tr')).map(tr => {
|
||||
const cell = (sel) => {
|
||||
const el = tr.querySelector(sel);
|
||||
return el ? el.textContent.trim() : null;
|
||||
};
|
||||
return {
|
||||
flight: cell('.flight-number'),
|
||||
airline: cell('.airline'),
|
||||
origin: cell('.origin'),
|
||||
destination: cell('.destination'),
|
||||
scheduled: cell('.time-scheduled'),
|
||||
estimated: cell('.time-estimated'),
|
||||
status: cell('.status'),
|
||||
gate: cell('.gate'),
|
||||
};
|
||||
})
|
||||
"""
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example-airport.com/departures")
|
||||
page.wait_for_selector("table.board tbody tr")
|
||||
rows = page.evaluate(READ_BOARD)
|
||||
```
|
||||
|
||||
One evaluation is one moment. Everything it returns came from the same DOM, which is the
|
||||
property you need and the one a Python-side loop cannot give you. The same reasoning
|
||||
applies to any table that updates itself, including
|
||||
[virtual scrolling tables](how-to-scrape-virtual-scrolling-tables-playwright.md), where
|
||||
the rows are also being recycled underneath you.
|
||||
|
||||
## Scheduled and estimated are different facts
|
||||
|
||||
Boards show a scheduled time, and once the flight is late, an estimated or actual time
|
||||
next to it. Collapsing them into one column destroys the only interesting thing on the
|
||||
board:
|
||||
|
||||
```python
|
||||
row["delay_minutes"] = None
|
||||
if row["scheduled"] and row["estimated"]:
|
||||
row["delay_minutes"] = minutes_between(row["scheduled"], row["estimated"])
|
||||
```
|
||||
|
||||
Compute the delay, do not store only the delay. When the board later revises the estimate,
|
||||
having both times lets you see the revision; having only a delay number means you cannot
|
||||
tell a corrected estimate from a worsening one.
|
||||
|
||||
Times on these boards are local to the airport and usually printed without a date or a
|
||||
zone. Attach both from context, not from the string:
|
||||
|
||||
```python
|
||||
row["airport"] = "BRS"
|
||||
row["service_date"] = board_date # read from the board header, not from today()
|
||||
```
|
||||
|
||||
Read the date from the board itself where it shows one. Around midnight, "today" on your
|
||||
machine and the board's service day are routinely different, and that is exactly when the
|
||||
delayed flights you care about are on screen.
|
||||
|
||||
## Key a row on flight plus service day plus direction
|
||||
|
||||
```python
|
||||
key = (row["airport"], row["direction"], row["flight"], row["service_date"])
|
||||
```
|
||||
|
||||
Direction belongs in the key because a code-shared arrival and departure can carry the
|
||||
same number at the same airport. Service day belongs in the key because a flight
|
||||
scheduled at 23:50 and departing at 00:40 exists on two calendar days, and the board will
|
||||
show it under one of them in a way you do not control.
|
||||
|
||||
Store status transitions instead of the last value:
|
||||
|
||||
```python
|
||||
if previous.get(key, {}).get("status") != row["status"]:
|
||||
write_event(key, row)
|
||||
```
|
||||
|
||||
A board is a live view. Its value as data is the sequence of states a flight passed
|
||||
through, which is lost the moment you keep only the current one.
|
||||
|
||||
## The board is a poll, so poll it politely
|
||||
|
||||
The page refreshes itself; you do not need to reload it. Keep one page open and read the
|
||||
snapshot on an interval, which is both lighter on the airport's servers and closer to what
|
||||
a person watching a board does:
|
||||
|
||||
```python
|
||||
import time
|
||||
while True:
|
||||
rows = page.evaluate(READ_BOARD)
|
||||
ingest(rows)
|
||||
time.sleep(120)
|
||||
```
|
||||
|
||||
Two minutes is enough for a board whose own refresh is around a minute. If the page stops
|
||||
updating, which happens when a tab is considered inactive, take a screenshot to check what
|
||||
is actually on screen before assuming the flights stopped moving, using
|
||||
[full page screenshots](how-to-take-full-page-screenshots-playwright.md). Longer loops
|
||||
also need the resilience described in
|
||||
[retrying failed requests](how-to-retry-failed-requests-playwright.md), because a run
|
||||
measured in hours will meet a network blip.
|
||||
|
||||
## Two things that quietly truncate the data
|
||||
|
||||
**The board paginates by time window.** Most show a few hours around now, with controls
|
||||
for earlier and later. A scraper that reads the default view has a partial day and no
|
||||
indication of it. Walk the windows explicitly.
|
||||
|
||||
**Cancelled and diverted rows leave the board.** They are removed rather than marked in
|
||||
many implementations. If you only store what is on screen, a cancellation looks like a
|
||||
flight that never existed. Compare each snapshot with the previous one and write the
|
||||
disappearance as an event.
|
||||
|
||||
## A complete watcher, with disappearance handled
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
AIRPORT, DIRECTION = "BRS", "departures"
|
||||
|
||||
def key_of(row, service_date):
|
||||
return (AIRPORT, DIRECTION, row["flight"], service_date)
|
||||
|
||||
previous, out_path = {}, "board.jsonl"
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open(out_path, "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
page.goto(f"https://example-airport.com/{DIRECTION}")
|
||||
page.wait_for_selector("table.board tbody tr")
|
||||
|
||||
while True:
|
||||
service_date = page.inner_text(".board-date").strip()
|
||||
rows = page.evaluate(READ_BOARD)
|
||||
observed = time.time()
|
||||
current = {}
|
||||
|
||||
for row in rows:
|
||||
k = key_of(row, service_date)
|
||||
current[k] = row
|
||||
before = previous.get(k)
|
||||
if before is None or before["status"] != row["status"] or before["estimated"] != row["estimated"]:
|
||||
out.write(json.dumps({
|
||||
"airport": AIRPORT, "direction": DIRECTION,
|
||||
"service_date": service_date, "observed_at": observed,
|
||||
"event": "seen", **row,
|
||||
}, ensure_ascii=False) + "\n")
|
||||
|
||||
for gone in set(previous) - set(current):
|
||||
out.write(json.dumps({
|
||||
"airport": AIRPORT, "direction": DIRECTION,
|
||||
"service_date": gone[3], "flight": gone[2],
|
||||
"observed_at": observed, "event": "left_board",
|
||||
"last_status": previous[gone]["status"],
|
||||
}) + "\n")
|
||||
|
||||
out.flush()
|
||||
previous = current
|
||||
time.sleep(120)
|
||||
```
|
||||
|
||||
The `left_board` event carries the last status seen, which is what makes it interpretable
|
||||
later. A flight that leaves the board an hour after "Departed" left normally; one that
|
||||
leaves while still "Delayed" is the cancellation you actually wanted to catch.
|
||||
|
||||
## Why a long-lived page is its own problem
|
||||
|
||||
This scraper does something unusual: it keeps one page open for hours. That avoids
|
||||
hammering the airport with reloads, and it introduces failure modes a request-per-read
|
||||
design never meets.
|
||||
|
||||
**The page stops refreshing.** Boards throttle their own updates when the tab looks
|
||||
inactive, and a headless context can look inactive permanently. The tell is a snapshot
|
||||
that stops changing while the wall clock moves. Guard on it explicitly rather than
|
||||
trusting the loop:
|
||||
|
||||
```python
|
||||
if rows == last_rows and time.time() - last_change > 900:
|
||||
page.reload()
|
||||
page.wait_for_selector("table.board tbody tr")
|
||||
last_change = time.time()
|
||||
```
|
||||
|
||||
**The session ages out.** Edge protection frequently issues a token with a lifetime, and
|
||||
when it expires the board silently stops updating or returns an interstitial in place of
|
||||
the table. A reload re-establishes it; a fresh context is the heavier fallback.
|
||||
|
||||
**A reload lands mid-render.** Waiting for the selector is not enough on its own, because
|
||||
the table exists before it is populated. Waiting for at least one row with a flight number
|
||||
is the version that does not read an empty board:
|
||||
|
||||
```python
|
||||
page.wait_for_function(
|
||||
"() => document.querySelectorAll('table.board tbody tr .flight-number').length > 0"
|
||||
)
|
||||
```
|
||||
|
||||
Underneath all three, the browser has to keep looking like a browser for hours rather than
|
||||
seconds, which is where a patched engine driven by stock Playwright earns its place. The
|
||||
order to debug a degraded read is in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md), and the
|
||||
resilience patterns for a run measured in hours are in
|
||||
[retrying failed requests](how-to-retry-failed-requests-playwright.md).
|
||||
|
||||
## What the event stream is worth
|
||||
|
||||
One row per state change, keyed on airport, direction, flight and service date, is what
|
||||
turns a live board into an answerable dataset:
|
||||
|
||||
- **Real punctuality**, computed from scheduled against the last estimate before
|
||||
departure, rather than from an airline's own published figure.
|
||||
- **How delays propagate**, by following the same aircraft's rotations across a day when
|
||||
the board exposes the inbound flight.
|
||||
- **Which gates and stands are chronically late**, which no public dataset publishes.
|
||||
- **Cancellation rate by route**, from `left_board` events with a non-departed last
|
||||
status.
|
||||
|
||||
None of these come from a snapshot table holding today's board. They all come from the
|
||||
transitions, which is why the loop above writes changes rather than states, and why the
|
||||
last status travels with the disappearance.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why should I read the whole board in one evaluation?** Because the board rewrites
|
||||
itself while you read. Iterating the DOM row by row from Python crosses into the page
|
||||
once per call, and a refresh between two calls gives you half of one board and half of
|
||||
the next. One evaluation returns one consistent snapshot.
|
||||
|
||||
**Scheduled, estimated, actual: which one do I store?** All of them, in separate
|
||||
fields. Collapsing them into a single time destroys the only thing a status board is
|
||||
for, which is the difference between what was planned and what happened.
|
||||
|
||||
**What key identifies a row?** Flight number plus service day plus direction.
|
||||
Direction belongs in the key because a code-shared arrival and a departure can carry
|
||||
the same number at the same airport on the same day.
|
||||
|
||||
**A flight disappeared from the board. Is that an error?** No, it is data. Boards show
|
||||
a window around now, so a flight leaves the board when it ages out. Record the
|
||||
disappearance with the last status you saw, or the series will look like the flight
|
||||
never landed.
|
||||
|
||||
**See also:** [How to scrape virtual scrolling tables with
|
||||
Playwright](how-to-scrape-virtual-scrolling-tables-playwright.md), [How to retry
|
||||
failed requests when scraping Playwright](how-to-retry-failed-requests-playwright.md),
|
||||
[How to scrape without getting blocked](how-to-scrape-without-getting-blocked.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Locators, https://playwright.dev/python/docs/api/class-locator -
|
||||
`locator.evaluate_all`, which runs one piece of JavaScript over every matching
|
||||
element, checked as the mechanism for taking a whole board in a single pass instead
|
||||
of one round trip per row.
|
||||
- This project's page on virtual scrolling tables, for the case where the board is
|
||||
windowed in the DOM as well as in time.
|
||||
@@ -0,0 +1,295 @@
|
||||
---
|
||||
title: "How to scrape fuel prices with Playwright"
|
||||
description: "Scrape fuel prices with Playwright: set the location explicitly instead of letting the site infer one, keep the grade and the currency unit with every price, and record who reported the number and when."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 152
|
||||
---
|
||||
|
||||
|
||||
# How to scrape fuel prices with Playwright
|
||||
|
||||
To scrape fuel prices, set the location **explicitly** and keep three things with every
|
||||
number: the grade, the unit, and who reported it. A fuel price page answers a question
|
||||
about a place, so the page has to decide where you are before it can show you anything,
|
||||
and if you do not decide for it the site decides from your exit IP.
|
||||
|
||||
That inference is the whole difficulty. A run through one proxy and a run through another
|
||||
return different stations and different prices for the same site and the same minute,
|
||||
and nothing in the captured row records which location produced it. The data looks
|
||||
noisy. It is not noisy, it is unlabelled.
|
||||
|
||||
This page covers pinning the location, reading a price table that mixes grades and
|
||||
units, and handling the fact that many of these prices are crowd-reported, not
|
||||
observed.
|
||||
|
||||
## Set the place before you read the price
|
||||
|
||||
Drive the site's own location control instead of relying on where it thinks you are:
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example.com/fuel-prices")
|
||||
|
||||
box = page.wait_for_selector("input[name='location'], input#search-location")
|
||||
box.click()
|
||||
box.type("Bristol", delay=90) # typed, not assigned
|
||||
page.keyboard.press("Enter")
|
||||
page.wait_for_selector(".station-list .station")
|
||||
```
|
||||
|
||||
Type into the field instead of setting its value. Location inputs are usually
|
||||
autocomplete widgets that only commit on a real key sequence, and a value written
|
||||
directly leaves the widget's internal state empty, so the search runs against nothing.
|
||||
The same pattern applies to any
|
||||
[autocomplete or typeahead input](how-to-scrape-autocomplete-typeahead-playwright.md).
|
||||
|
||||
Where the site offers no control and geolocates silently, you are in the territory of
|
||||
[geotargeted content](how-to-scrape-geotargeted-content-playwright.md), and the exit you
|
||||
browse from becomes part of the query whether you like it or not. Record it either way:
|
||||
|
||||
```python
|
||||
row["queried_location"] = "Bristol"
|
||||
```
|
||||
|
||||
A dataset of fuel prices without a location column is not recoverable later. Write the
|
||||
column even when it feels redundant.
|
||||
|
||||
## Grade and unit belong to the number
|
||||
|
||||
Fuel prices come as a small matrix: several grades per station, each with a price, in a
|
||||
unit that varies by country and sometimes by page. Read the matrix as a matrix:
|
||||
|
||||
```python
|
||||
stations = []
|
||||
for card in page.query_selector_all(".station-list .station"):
|
||||
prices = []
|
||||
for row in card.query_selector_all(".fuel-row"):
|
||||
prices.append({
|
||||
"grade": row.query_selector(".grade").inner_text().strip(),
|
||||
"price_text": row.query_selector(".price").inner_text().strip(),
|
||||
})
|
||||
stations.append({
|
||||
"name": card.query_selector(".name").inner_text().strip(),
|
||||
"address": card.query_selector(".address").inner_text().strip(),
|
||||
"prices": prices,
|
||||
})
|
||||
```
|
||||
|
||||
Keep `price_text` unparsed at capture time. The string carries the unit and the currency,
|
||||
and those are exactly what a naive float conversion throws away. Parse it in a second
|
||||
step where the failure is visible:
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
MONEY = re.compile(r"(?P<sym>[$€£]|\b[A-Z]{3}\b)?\s*(?P<amount>\d+[.,]\d+)\s*(?P<per>/\s*\w+)?")
|
||||
|
||||
def parse_price(text):
|
||||
m = MONEY.search(text)
|
||||
if not m:
|
||||
return None
|
||||
return {
|
||||
"amount": float(m.group("amount").replace(",", ".")),
|
||||
"currency": m.group("sym"),
|
||||
"per": (m.group("per") or "").lstrip("/ ").strip() or None,
|
||||
}
|
||||
```
|
||||
|
||||
The `per` group matters more than it looks. The same page can show a price per litre and
|
||||
a price per gallon in different regions, and a series that silently mixes them produces a
|
||||
chart with a step in it that no one can explain.
|
||||
|
||||
## Most of these prices are reports, not observations
|
||||
|
||||
A large share of fuel price sites are crowd-sourced. The number is what a visitor said
|
||||
they paid, at a time they may not have recorded accurately. Sites usually show this next
|
||||
to the price as an age, a username, or a confidence marker. Capture it:
|
||||
|
||||
```python
|
||||
"reported_age": row.query_selector(".age").inner_text().strip()
|
||||
if row.query_selector(".age") else None,
|
||||
```
|
||||
|
||||
A price reported two hours ago and a price reported nine days ago are not comparable
|
||||
data points, and the difference is often the largest source of variance in the whole
|
||||
dataset. Sites that publish operator-fed prices instead usually say so; record which kind
|
||||
of source you are reading, per station, because a single site can carry both.
|
||||
|
||||
## Walking a region without hammering the search
|
||||
|
||||
To cover an area, iterate over places instead of paginating a single huge result set:
|
||||
|
||||
```python
|
||||
for place in ["Bristol", "Bath", "Weston-super-Mare"]:
|
||||
set_location(page, place)
|
||||
harvest(page)
|
||||
page.wait_for_timeout(3000)
|
||||
```
|
||||
|
||||
This is slower than requesting a wide radius, and it is the version that works. Wide
|
||||
radius queries on these sites are commonly capped at a fixed number of results with no
|
||||
indication that anything was dropped, so a national sweep with three requests returns a
|
||||
confident subset. If you do use radius, look for a total count in the response and check
|
||||
it against the number of rows you received.
|
||||
|
||||
Keep the pace conservative and the run scheduled, not continuous. Prices move a
|
||||
few times a day at most, so a poll loop buys nothing and costs the goodwill described in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## Store it in long form
|
||||
|
||||
One row per station per grade per observation, with location, unit, source type and both
|
||||
timestamps. It is more rows than a wide table with one column per grade, and it is the
|
||||
shape that survives a site adding a grade, dropping one, or changing the unit in one
|
||||
region. Writing it as you go, in
|
||||
[a SQLite database](how-to-scrape-into-a-database-playwright.md) or
|
||||
[JSON Lines](how-to-scrape-to-json-lines-playwright.md), also means an interrupted run
|
||||
leaves usable data rather than nothing.
|
||||
|
||||
## A complete pass over several towns
|
||||
|
||||
```python
|
||||
import json, re, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
PLACES = ["Bristol", "Bath", "Weston-super-Mare"]
|
||||
|
||||
def set_location(page, place):
|
||||
box = page.wait_for_selector("input[name='location'], input#search-location")
|
||||
box.click()
|
||||
box.fill("")
|
||||
box.type(place, delay=90)
|
||||
page.keyboard.press("Enter")
|
||||
page.wait_for_selector(".station-list .station, .no-results")
|
||||
|
||||
def harvest(page, place):
|
||||
if page.query_selector(".no-results"):
|
||||
return []
|
||||
rows = []
|
||||
for card in page.query_selector_all(".station-list .station"):
|
||||
name = card.query_selector(".name").inner_text().strip()
|
||||
address = card.query_selector(".address").inner_text().strip()
|
||||
for fuel in card.query_selector_all(".fuel-row"):
|
||||
price_text = fuel.query_selector(".price").inner_text().strip()
|
||||
age = fuel.query_selector(".age")
|
||||
rows.append({
|
||||
"queried_location": place,
|
||||
"station": name,
|
||||
"address": address,
|
||||
"grade": fuel.query_selector(".grade").inner_text().strip(),
|
||||
"price_text": price_text,
|
||||
"price": parse_price(price_text),
|
||||
"reported_age": age.inner_text().strip() if age else None,
|
||||
"observed_at": time.time(),
|
||||
})
|
||||
return rows
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("fuel.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example.com/fuel-prices")
|
||||
for place in PLACES:
|
||||
set_location(page, place)
|
||||
for row in harvest(page, place):
|
||||
out.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(4000)
|
||||
```
|
||||
|
||||
The `box.fill("")` before typing is the line that stops the second town from being
|
||||
searched as "BristolBath". Autocomplete widgets keep their previous value and their
|
||||
internal selection, and clearing the field is what resets both.
|
||||
|
||||
## Why fuel sites are unusually defensive
|
||||
|
||||
These sites carry commercially valuable data that competitors want in bulk, so they tend
|
||||
to be better defended than their size suggests, and the defence is usually aimed at the
|
||||
request rather than the person. Three consequences shape the design above.
|
||||
|
||||
**A side HTTP client rarely gets the list.** The search result is fetched by the page after
|
||||
the location commits, from an endpoint that expects the browser's context. Driving the
|
||||
real control in a real browser is what keeps the response coming, which is why the code
|
||||
types rather than building a URL.
|
||||
|
||||
**Degradation looks like an empty town.** When the protection is unhappy the list renders
|
||||
with zero cards and no error. That is indistinguishable from a town with no stations
|
||||
unless you check the negative case explicitly, which is what the `.no-results` branch is
|
||||
for. Treat "cards absent and no-results absent" as a failed read rather than an empty one:
|
||||
|
||||
```python
|
||||
if not page.query_selector(".station-list .station") and not page.query_selector(".no-results"):
|
||||
raise RuntimeError("neither stations nor a no-results marker: failed read")
|
||||
```
|
||||
|
||||
**Your exit becomes part of the query.** Even with a location typed in, some sites blend
|
||||
the inferred position into ranking or availability. Pin the exit for a series rather than
|
||||
letting it rotate, or the same town will return different stations on different days for
|
||||
reasons that have nothing to do with fuel. The general form is in
|
||||
[scraping geotargeted content](how-to-scrape-geotargeted-content-playwright.md), and the
|
||||
debug order when a read degrades is in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## Turning reports into a series you can trust
|
||||
|
||||
Crowd-reported prices need one more step before they are comparable: a freshness filter
|
||||
applied at read time, not at capture.
|
||||
|
||||
```python
|
||||
def usable(row, max_age_hours=48):
|
||||
age = row.get("reported_age") or ""
|
||||
m = re.search(r"(\d+)\s*(hour|day|week)", age, re.I)
|
||||
if not m:
|
||||
return False # unknown age: not comparable
|
||||
n, unit = int(m.group(1)), m.group(2).lower()
|
||||
hours = n * {"hour": 1, "day": 24, "week": 168}[unit]
|
||||
return hours <= max_age_hours
|
||||
```
|
||||
|
||||
Filtering at read time keeps the stale rows in the archive, where they still answer
|
||||
questions about reporting behaviour, while keeping them out of a price average that would
|
||||
otherwise be dominated by whichever station has the most enthusiastic reporter.
|
||||
|
||||
The series is then one row per station, grade and observation, with `queried_location`,
|
||||
`unit`, `currency`, `reported_age` and `observed_at`. That is enough to answer where fuel
|
||||
is cheapest today, how fast a price change propagates across a chain, and how stale a
|
||||
given site's data really is, which is the question the site itself will never answer.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why do two runs return different stations for the same site?** Because the page
|
||||
decides where you are before it shows you anything, and with no explicit location it
|
||||
decides from the exit IP. The data is not noisy, it is unlabelled: write the queried
|
||||
location into every row and the difference becomes readable.
|
||||
|
||||
**Why does typing into the location box work when setting the value does not?**
|
||||
Location fields are usually autocomplete widgets that only commit on a real key
|
||||
sequence. A value written straight into the element leaves the widget's internal state
|
||||
empty, so the search runs against nothing.
|
||||
|
||||
**Should I convert the price to a float at capture time?** No. The string carries the
|
||||
currency and the unit, and those are exactly what a float conversion throws away. A
|
||||
page can show a price per litre and a price per gallon in different regions, and a
|
||||
series that mixes them has a step nobody can explain.
|
||||
|
||||
**How reliable are these prices?** Many fuel price sites are crowd-sourced, so the
|
||||
number is what a visitor said they paid. Capture the reported age next to it: a price
|
||||
from two hours ago and one from nine days ago are not comparable, and that gap is
|
||||
often the largest source of variance you have.
|
||||
|
||||
**See also:** [Scrape autocomplete and typeahead inputs with
|
||||
Playwright](how-to-scrape-autocomplete-typeahead-playwright.md), [How to scrape
|
||||
geotargeted content with Playwright](how-to-scrape-geotargeted-content-playwright.md),
|
||||
[How to rate limit your own Playwright
|
||||
scraper](how-to-rate-limit-your-scraper-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Input, https://playwright.dev/python/docs/input - `locator.fill()`,
|
||||
which focuses the element and fires an input event, and `press_sequentially()`,
|
||||
which types character by character with an optional delay. Checked for why an
|
||||
autocomplete commits on typing and not on an assigned value.
|
||||
- This project's pages on autocomplete inputs and on geotargeted content, which carry
|
||||
the two mechanics this page depends on.
|
||||
@@ -83,7 +83,7 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
Two details matter more than they look. First, click the calendar days, do not type into
|
||||
a read-only date input: many pickers ignore a value you set directly and only commit the
|
||||
range on a real click, so a typed date produces a search that silently uses today. Second,
|
||||
the mouse arriving at each day on a curved path rather than teleporting is not decoration
|
||||
the mouse arriving at each day on a curved path instead of teleporting is not decoration
|
||||
here. A rate scan fires the same occupancy widget dozens of times in a session, and a
|
||||
control that is always clicked at the exact same pixel with zero travel between clicks is
|
||||
one of the cheapest interaction signals a site can watch for.
|
||||
@@ -117,7 +117,7 @@ Arming [`expect_response`](https://playwright.dev/python/docs/api/class-page#pag
|
||||
you click first and wait second, the response can arrive in the gap and you wait forever.
|
||||
Keying the predicate on both the URL fragment and `status == 200` matters too, because a
|
||||
rate call that comes back empty or with a non-200 is exactly the failure mode the next
|
||||
section is about, and you want to see it as a failure rather than silently read an empty
|
||||
section is about, and you want to see it as a failure, not silently read an empty
|
||||
body. For the general version of this timing problem, see [how to wait for the right
|
||||
signal instead of a fixed delay](how-to-wait-for-page-load-playwright.md).
|
||||
|
||||
|
||||
@@ -63,8 +63,8 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
# `browser` is a real Playwright Browser; every documented method works.
|
||||
```
|
||||
|
||||
The `seed=42` fixes the identity so a run that fails on one tile can be replayed exactly
|
||||
rather than guessed at. See the [quickstart](quickstart.md) for what the seed pins.
|
||||
The `seed=42` fixes the identity so a run that fails on one tile can be replayed exactly,
|
||||
not guessed at. See the [quickstart](quickstart.md) for what the seed pins.
|
||||
|
||||
## Trigger the lazy-load by scrolling each tile into view
|
||||
|
||||
@@ -113,7 +113,7 @@ def promote_tile(page, handle):
|
||||
|
||||
## Resolve the highest-resolution srcset candidate
|
||||
|
||||
Once a tile is real, you often have a choice rather than a URL. A
|
||||
Once a tile is real, you often have a choice, not a URL. A
|
||||
[`srcset`](https://html.spec.whatwg.org/multipage/images.html) is a list of `url
|
||||
widthDescriptor` pairs, and the browser picks one for its layout, which is not the one
|
||||
you want. You want the largest. Parse the attribute yourself and take the widest
|
||||
@@ -159,7 +159,7 @@ the asset behind the lightbox. That larger asset is the next step.
|
||||
|
||||
The grid rarely holds the full image. Clicking a tile opens a lightbox or detail view
|
||||
that loads a bigger asset, and that is the one worth keeping. Click, wait for the larger
|
||||
image to appear, and read its resolved URL from the live element rather than the markup:
|
||||
image to appear, and read its resolved URL from the live element instead of the markup:
|
||||
|
||||
```python
|
||||
def full_res_url(page, tile_selector):
|
||||
|
||||
@@ -15,7 +15,7 @@ on the next one, because a fixed sleep is a guess about a network and a render p
|
||||
you do not control.
|
||||
|
||||
This page is the loop that does not guess: how to wait for content to actually arrive,
|
||||
how to know when the page is really done rather than just slow, how to dedupe what you
|
||||
how to know when the page is really done, not just slow, how to dedupe what you
|
||||
collect, and the part generic scroll tutorials skip entirely - a perfectly mechanical
|
||||
scroll loop is itself something a page can notice, and the block that shows up minutes
|
||||
into a session is usually that, not your fingerprint.
|
||||
@@ -119,7 +119,7 @@ exists.
|
||||
## Deduplicating items across scrolls
|
||||
|
||||
Scroll-and-collect naturally re-reads items you already have, because the DOM keeps
|
||||
everything loaded so far rather than replacing it. Track what you have already recorded
|
||||
everything loaded so far instead of replacing it. Track what you have already recorded
|
||||
by a stable identifier, not by position:
|
||||
|
||||
```python
|
||||
@@ -142,7 +142,7 @@ def harvest(page):
|
||||
})
|
||||
```
|
||||
|
||||
Call `harvest(page)` after each successful growth round rather than only once at the end.
|
||||
Call `harvest(page)` after each successful growth round, not only once at the end.
|
||||
Two reasons: it lets you inspect progress while the loop still runs, and it means a crash
|
||||
or a block partway through still leaves you with everything collected up to that point
|
||||
instead of nothing.
|
||||
@@ -163,7 +163,7 @@ read anything, and fires at a rate no human scrolling with a mouse or trackpad p
|
||||
that is a behavioral signature, and it is a different layer entirely from the fingerprint.
|
||||
[The checklist for one-site detection](playwright-detected-as-bot.md) puts behavior at
|
||||
step five for a reason: blocks that arrive **after an interaction**, minutes into a
|
||||
session rather than at the first request, are usually this rather than anything about the
|
||||
session, not at the first request, are usually this, not anything about the
|
||||
browser's reported GPU or fonts. A perfectly consistent fingerprint does not help if the
|
||||
scrolling pattern on top of it is the part that stood out.
|
||||
|
||||
@@ -177,7 +177,7 @@ looked fine to a check that was only watching for an exception.
|
||||
|
||||
The fix is the same one this project applies to pointer movement: vary the motion instead
|
||||
of repeating it, and derive the variation from a seed so a run that misbehaves can be
|
||||
replayed rather than re-guessed.
|
||||
replayed, not re-guessed.
|
||||
|
||||
```python
|
||||
import random
|
||||
@@ -197,14 +197,14 @@ with sf as browser:
|
||||
|
||||
That pause is not the thing telling you content arrived - `wait_for_function` still is,
|
||||
exactly as before. It only changes how long the loop dwells between wheel events, so the
|
||||
gaps look like a device scrolling rather than a timer firing at a fixed interval. Wire
|
||||
gaps look like a device scrolling instead of a timer firing at a fixed interval. Wire
|
||||
`human_scroll_step` in as the scroll action inside `scroll_until_stable` and the growth
|
||||
check around it does not change at all.
|
||||
|
||||
The same idea already ships for clicks and hovers: [humanized mouse
|
||||
movement](human-mouse-movement.md) is on by default in this project, driven from the same
|
||||
per-session seed, so the arc to a button and the pacing of a scroll come from one
|
||||
consistent identity rather than two unrelated randomizers. Bezier curves get the pointer
|
||||
consistent identity, not two unrelated randomizers. Bezier curves get the pointer
|
||||
path right; what actually gets read on a scroll loop is closer to timing than shape, since
|
||||
a wheel event does not carry the same rich field set a pointer move does - but a constant
|
||||
interval is exactly as loud as a teleporting cursor, and for the same reason.
|
||||
@@ -238,7 +238,7 @@ a bug.
|
||||
|
||||
An infinite-scroll loop that works on every page you throw it at waits for the DOM to
|
||||
actually grow and for the network to actually settle, stops on a streak of flat rounds
|
||||
rather than one, and keys its dedup on an identifier rather than position. None of that
|
||||
instead of one, and keys its dedup on an identifier, not position. None of that
|
||||
is specific to this project; it is just Playwright used the way its own waiting primitives
|
||||
are meant to be used.
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ nav_order: 26
|
||||
# How to scrape job postings with Playwright
|
||||
|
||||
To scrape job postings with Playwright, drive the board's faceted search controls instead
|
||||
of walking URLs, wait for the specific results XHR rather than for `networkidle`, and read
|
||||
of walking URLs, wait for the specific results XHR, not for `networkidle`, and read
|
||||
each posting from its `JobPosting` JSON-LD instead of brittle card selectors. Run the whole
|
||||
sweep under one stable browser identity so the board sees a returning visitor, and pace it
|
||||
so the request volume does not give you away.
|
||||
|
||||
@@ -151,7 +151,7 @@ The `complete && naturalWidth > 0` check is the important part. `scroll_into_vie
|
||||
returns as soon as the element is positioned, which is before the observer has swapped the
|
||||
URL and long before the image has decoded. Reading `src` on the line after the scroll gets
|
||||
you the placeholder again. Waiting on `naturalWidth` asserts a positive fact, that a real
|
||||
image with real dimensions is present, rather than the absence of an error.
|
||||
image with real dimensions is present, not the absence of an error.
|
||||
|
||||
If the gallery itself grows as you scroll, this is really two problems stacked, and the
|
||||
lazy-image read has to run inside the
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
---
|
||||
title: "How to scrape library catalog availability with Playwright"
|
||||
description: "Scrape library catalogue availability with Playwright: read holdings per branch, not per title, keep the loan status vocabulary the catalogue uses, and handle the session the OPAC hands you."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 154
|
||||
---
|
||||
|
||||
|
||||
# How to scrape library catalog availability with Playwright
|
||||
|
||||
To scrape catalogue availability, read the **holdings table**, not the title page. A
|
||||
library record is one work with many physical copies, each at a branch, each with its own
|
||||
status, and the headline "Available" on the record page is a summary that hides which
|
||||
branch has it and how many copies are out.
|
||||
|
||||
Public catalogues also carry a second surprise: they are session-driven. The search you
|
||||
run creates server-side state, results are addressed by a token that expires, and a URL
|
||||
copied from one run frequently returns an empty result set in the next. Scraping them by
|
||||
saving result URLs produces a script that works once.
|
||||
|
||||
This page covers driving the search instead of replaying URLs, reading holdings per
|
||||
copy, and keeping the catalogue's own status words instead of flattening them to a
|
||||
boolean.
|
||||
|
||||
## Drive the search, do not replay the result URL
|
||||
|
||||
Run the query in the browser and read the results in the same session:
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://catalog.example.org/")
|
||||
|
||||
page.fill("input[name='q']", "the master and margarita")
|
||||
page.press("input[name='q']", "Enter")
|
||||
page.wait_for_selector(".result-item, .no-results")
|
||||
|
||||
hits = []
|
||||
for item in page.query_selector_all(".result-item"):
|
||||
link = item.query_selector("a.title")
|
||||
hits.append({
|
||||
"title": link.inner_text().strip(),
|
||||
"href": link.get_attribute("href"),
|
||||
})
|
||||
```
|
||||
|
||||
Keep `href` relative and resolve it against `page.url` when you follow it. Catalogue
|
||||
links routinely embed the session token in the path, and an absolute URL captured today
|
||||
is a dead link tomorrow. Following it inside the same browser session works because the
|
||||
token is still the one the server issued you.
|
||||
|
||||
## Holdings are per copy, per branch
|
||||
|
||||
Open a record and read the holdings table instead of the availability badge:
|
||||
|
||||
```python
|
||||
def holdings(page):
|
||||
rows = []
|
||||
for tr in page.query_selector_all("table.holdings tbody tr"):
|
||||
cells = [td.inner_text().strip() for td in tr.query_selector_all("td")]
|
||||
if len(cells) < 3:
|
||||
continue
|
||||
rows.append({
|
||||
"branch": cells[0],
|
||||
"call_number": cells[1],
|
||||
"status": cells[2],
|
||||
"due": cells[3] if len(cells) > 3 else None,
|
||||
})
|
||||
return rows
|
||||
```
|
||||
|
||||
One row per physical copy is the right grain. It answers "which branch can I walk to
|
||||
today", which the record-level badge cannot, and it makes the count of copies visible,
|
||||
which matters for anything about demand. A record with nine copies all on loan is a very
|
||||
different signal from one copy on loan, and both render as "Checked out" at the top of
|
||||
the page.
|
||||
|
||||
## Keep the catalogue's words
|
||||
|
||||
Resist mapping status to a boolean at capture time. Library systems use a vocabulary that
|
||||
carries real distinctions:
|
||||
|
||||
- **Available** and **On shelf** mean you can take it now.
|
||||
- **Checked out** has a due date. **On hold** does not, and means someone is waiting.
|
||||
- **In transit** is between branches, so it is available soon but not anywhere now.
|
||||
- **Reference only**, **Reserve**, **Staff use**, **Missing**, **On order**, **Withdrawn**
|
||||
are all non-available for different reasons, and only some of them ever become
|
||||
available again.
|
||||
|
||||
Store the raw string and derive a boolean at read time if you need one. The mapping from
|
||||
these words to availability differs between library systems, and a mapping baked into the
|
||||
capture is a decision you cannot revisit without re-scraping.
|
||||
|
||||
## The three mechanical traps
|
||||
|
||||
**Consent and session interstitials.** Many public catalogues put a terms banner or a
|
||||
branch selector in front of the first search. Clear it once at the start of the session,
|
||||
the same way you would any
|
||||
[cookie consent banner](how-to-handle-cookie-consent-banners-playwright.md), and the rest
|
||||
of the run is clean.
|
||||
|
||||
**Results paginate server-side against the session.** The "next" control posts back
|
||||
rather than changing a query string. Click it and wait for the list to change instead of
|
||||
constructing page numbers, which is the pattern in
|
||||
[scraping paginated pages](how-to-scrape-paginated-pages-playwright.md).
|
||||
|
||||
**Holdings load after the record.** On several widely used platforms the holdings table
|
||||
arrives in a second request and the record page renders complete without it. Wait for the
|
||||
table specifically, and treat its absence after a timeout as a distinct outcome rather
|
||||
than as an empty holdings list.
|
||||
|
||||
## Scrape the catalogue, not the patron account
|
||||
|
||||
Everything above works against the public catalogue with no login. It is worth being
|
||||
explicit that the interesting-looking parts behind a library card, such as your loans,
|
||||
holds and fines, are personal data attached to a person, and the general point in
|
||||
[why automating login is riskier than reusing a session](automating-login-vs-session-reuse.md)
|
||||
applies with extra force when the account is a library record.
|
||||
|
||||
The public catalogue is enough for availability questions, and it is the part libraries
|
||||
publish deliberately.
|
||||
|
||||
## Pace it, and prefer a narrow question
|
||||
|
||||
Libraries run these systems on small budgets and the search endpoint is the expensive one.
|
||||
A run that walks an entire catalogue is both slow and unkind. Pick the titles you actually
|
||||
care about, poll them at a human interval, and use
|
||||
[the rate limiting rules](how-to-rate-limit-your-scraper-playwright.md) rather than
|
||||
running flat out. Availability changes when someone physically returns a book, which is a
|
||||
scale measured in days.
|
||||
|
||||
## A complete watch over a shortlist
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
WATCHLIST = [
|
||||
"the master and margarita",
|
||||
"gödel escher bach",
|
||||
"the making of the atomic bomb",
|
||||
]
|
||||
|
||||
def search(page, query):
|
||||
page.goto("https://catalog.example.org/")
|
||||
dismiss_interstitials(page)
|
||||
page.fill("input[name='q']", query)
|
||||
page.press("input[name='q']", "Enter")
|
||||
page.wait_for_selector(".result-item, .no-results")
|
||||
return page.query_selector_all(".result-item")
|
||||
|
||||
def dismiss_interstitials(page):
|
||||
for sel in (".terms-accept", ".cookie-accept", ".branch-select-skip"):
|
||||
node = page.query_selector(sel)
|
||||
if node:
|
||||
node.click()
|
||||
page.wait_for_timeout(300)
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("holdings.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
for query in WATCHLIST:
|
||||
items = search(page, query)
|
||||
if not items:
|
||||
out.write(json.dumps({"query": query, "observed_at": time.time(),
|
||||
"result": "no_match"}) + "\n")
|
||||
continue
|
||||
items[0].query_selector("a.title").click()
|
||||
page.wait_for_selector("table.holdings tbody tr", timeout=15000)
|
||||
for copy in holdings(page):
|
||||
copy.update({"query": query, "record_url": page.url,
|
||||
"observed_at": time.time()})
|
||||
out.write(json.dumps(copy, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(4000)
|
||||
```
|
||||
|
||||
Clicking the result rather than navigating to its `href` is what keeps the session token
|
||||
valid, and it is the difference between a script that works today and one that works next
|
||||
month. Note that `record_url` is stored anyway: it is useless as a link later, and it is
|
||||
the only way to tell which of three editions you actually read.
|
||||
|
||||
## Why these systems fail in ways that look like data
|
||||
|
||||
Library catalogues are rarely defended against scraping in the adversarial sense. They
|
||||
break for a duller reason: they are session-driven enterprise software running on modest
|
||||
hardware, and under load they degrade rather than refuse.
|
||||
|
||||
Three degradations produce plausible wrong data, and each needs a positive check.
|
||||
|
||||
**The session expires mid-run.** The next search returns the landing page instead of
|
||||
results, which parses as zero hits. Detect it by asserting the search box still exists
|
||||
after the results wait, and restart the session rather than recording an absence.
|
||||
|
||||
**Holdings arrive late or not at all.** The record page renders complete without its
|
||||
holdings table, so a short timeout writes a book with no copies:
|
||||
|
||||
```python
|
||||
try:
|
||||
page.wait_for_selector("table.holdings tbody tr", timeout=15000)
|
||||
except Exception:
|
||||
record = {"query": query, "result": "holdings_not_loaded", "observed_at": time.time()}
|
||||
```
|
||||
|
||||
A distinct outcome, not an empty list. The two are opposite facts and only one of them is
|
||||
about the library.
|
||||
|
||||
**A branch filter you did not set.** Some catalogues remember a branch from an earlier
|
||||
session and scope holdings to it silently. If a title you know is held system-wide comes
|
||||
back with one copy, check for a scope control before believing the number.
|
||||
|
||||
None of these are anti-bot measures, which is worth saying plainly: not every failed read
|
||||
is a defence. The debug order in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md) still applies,
|
||||
starting with the cheapest check, which here is a screenshot of what the page actually
|
||||
showed.
|
||||
|
||||
## What the copy-level history is good for
|
||||
|
||||
One row per copy per observation, keyed on `(record_url, branch, call_number)`, with the
|
||||
raw status string and the due date. That grain answers questions the library's own
|
||||
interface does not:
|
||||
|
||||
- **How long is the real wait.** Not the hold queue length, but how many days pass between
|
||||
a copy going out and coming back, averaged over months.
|
||||
- **Which branch actually stocks a subject.** Copy counts per branch over time, rather
|
||||
than a single snapshot that reflects who happened to borrow that week.
|
||||
- **Whether a title is quietly disappearing.** Copies moving to `Missing` or `Withdrawn`
|
||||
and never returning is a signal the catalogue does not surface anywhere.
|
||||
|
||||
All three need history, which is why the write is append-only and the status string is
|
||||
kept verbatim. A table holding the current availability per title answers none of them,
|
||||
and is also the exact thing the library's own search page already does better.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Can I just save the result URL and reload it later?** Usually not. Public catalogues
|
||||
carry the search in session state, so a replayed result URL returns an empty set or a
|
||||
fresh session. Run the query in the browser and read the results in the same session.
|
||||
|
||||
**Why does the availability badge disagree with the holdings table?** The badge
|
||||
summarises, the table states. Availability is per copy and per branch, so a record
|
||||
showing available can still have nothing on the shelf at the branch you care about.
|
||||
|
||||
**Should I normalise the status to available or not available?** Not at capture time.
|
||||
Library systems use a vocabulary that carries real distinctions - in transit, on hold,
|
||||
reference only, missing - and collapsing it to a boolean throws away the part that
|
||||
answers most questions.
|
||||
|
||||
**Is any of this touching patron data?** No, and it should stay that way. Everything
|
||||
here works against the public catalogue with no login. A patron account is a different
|
||||
system with a different answer.
|
||||
|
||||
**See also:** [How to handle cookie consent banners in
|
||||
Playwright](how-to-handle-cookie-consent-banners-playwright.md), [How to scrape
|
||||
paginated pages with Playwright](how-to-scrape-paginated-pages-playwright.md), [How to
|
||||
rate limit your own Playwright scraper](how-to-rate-limit-your-scraper-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Locators, https://playwright.dev/python/docs/api/class-locator - the
|
||||
locator model and clicking a result instead of navigating to its href, checked for
|
||||
keeping a session token valid across a search and its record pages.
|
||||
- This project's pages on consent interstitials and on pacing, which describe the two
|
||||
failure modes this page runs into most.
|
||||
@@ -0,0 +1,192 @@
|
||||
---
|
||||
title: "Download and read PDFs linked from a page with Playwright"
|
||||
description: "Download PDFs linked from a page with Playwright: find every link by content type, fetch through page.request so cookies carry over, then extract the text."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 149
|
||||
---
|
||||
|
||||
|
||||
# Download and read PDFs linked from a page with Playwright
|
||||
|
||||
Downloading PDFs linked from a page is three jobs, not one: find every link that
|
||||
actually resolves to a PDF, even ones hidden behind a redirect or a bare query
|
||||
string; fetch the bytes through the page's own session so an auth wall does not
|
||||
refuse you; then run the file through a PDF library to pull the text out. Skip the
|
||||
session part and a plain HTTP client gets HTML or a 403 instead of a document.
|
||||
|
||||
## Find every link that actually resolves to a PDF
|
||||
|
||||
A `.pdf` extension in the URL is a hint, not a guarantee. Plenty of real PDF links lack
|
||||
one: a download endpoint like `/reports/export?id=42&format=pdf`, or a redirector that
|
||||
sends a 302 elsewhere before the bytes arrive. Trusting the extension misses both, and
|
||||
the DOM gives you the absolute URL for free, so start there:
|
||||
|
||||
```python
|
||||
candidates = page.eval_on_selector_all("a[href]", "els => els.map(e => e.href)")
|
||||
```
|
||||
|
||||
Measured on a local page carrying a relative link, an absolute one with a query string
|
||||
and one non-PDF link, that call returned all three fully resolved, query string intact.
|
||||
The extension filter narrows the list cheaply; the content type is what confirms it, and
|
||||
the next section is where that happens.
|
||||
|
||||
## Getting the bytes: one route works, three do not
|
||||
|
||||
This is the part where most examples on the web are wrong for Firefox, so here is what
|
||||
was measured on 5 September 2026, all four routes against the same local page.
|
||||
|
||||
**What works: `fetch` from inside the page.** The request leaves the browser itself, with
|
||||
the session's cookies attached, and comes back as bytes you can write to disk.
|
||||
|
||||
```python
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
res = page.evaluate("""async (u) => {
|
||||
const r = await fetch(u, {credentials: 'include'});
|
||||
const buf = new Uint8Array(await r.arrayBuffer());
|
||||
let s = ''; for (const x of buf) s += String.fromCharCode(x);
|
||||
return {status: r.status, type: r.headers.get('content-type'), b64: btoa(s)};
|
||||
}""", url)
|
||||
|
||||
if "application/pdf" in (res["type"] or ""):
|
||||
Path("report.pdf").write_bytes(base64.b64decode(res["b64"]))
|
||||
```
|
||||
|
||||
That returned `200`, `application/pdf` and 1388 bytes on the test file, and the content
|
||||
type in the same response is your filter: one request answers both "is it a PDF" and
|
||||
"give me the PDF". Base64 through `evaluate` is the price of moving binary across the
|
||||
protocol boundary; for very large files, prefer the download route below.
|
||||
|
||||
**What does not work, and why it matters:**
|
||||
|
||||
`page.goto(pdf_url)` returns `None` instead of a response. Firefox hands the PDF to its
|
||||
built-in viewer, so there is no ordinary navigation response to call `.body()` on. The
|
||||
URL changes, the viewer renders, and your code gets nothing. Measured: `response is
|
||||
None`, `document.contentType` confirming the viewer took over.
|
||||
|
||||
`page.expect_download()` around a click on a plain link times out, for the same reason:
|
||||
the viewer opens instead of a download starting. It is the right API when the server
|
||||
sends `Content-Disposition: attachment`, and the wrong one for a link the browser thinks
|
||||
it can display.
|
||||
|
||||
`page.request` / `APIRequestContext` is refused outright on this engine, by design. The
|
||||
error says why: HTTP performed outside the page is not browser automation and carries
|
||||
none of the browser's identity, so a request that looks nothing like the browser making
|
||||
it would be a hole in the very thing this engine exists to keep consistent. On stock
|
||||
Playwright it works; here you use the in-page `fetch` above.
|
||||
|
||||
## Why a plain requests.get so often comes back as HTML or a 403
|
||||
|
||||
Pointing a separate Python client at the same URL frequently fails where the browser
|
||||
succeeds, for two independent reasons. First, a PDF gated behind a login has no
|
||||
session to present: a bare `requests.get()` carries none of the cookies the browser
|
||||
earned by signing in, so the server answers with a login page instead of the file.
|
||||
Second, even a public PDF can sit behind a defense that fingerprints the TLS
|
||||
handshake and header order, and a generic client's handshake does not match a
|
||||
browser's; the response is an interstitial or a flat `403` instead of bytes. Fetching with `fetch` from inside the page avoids both, because the request leaves the
|
||||
browser itself: same cookies, same handshake, same header order as every other request
|
||||
that page has already made. That is also why this engine refuses the out-of-page request
|
||||
API rather than offering it as a convenience.
|
||||
|
||||
## Name files deterministically, so a rerun does not duplicate work
|
||||
|
||||
Hash the source URL into the filename and every PDF gets a stable name that survives a
|
||||
rerun without a second copy appearing under a different one:
|
||||
|
||||
```python
|
||||
import hashlib
|
||||
name = hashlib.sha1(url.encode()).hexdigest()[:16] + ".pdf"
|
||||
```
|
||||
|
||||
The tempting alternative is the last path segment, and it breaks on the first URL with a
|
||||
query string: `annex.pdf?v=2` becomes a filename with a `?` in it, which Windows refuses
|
||||
outright. Strip anything from the first `?` or `#` before you use it, or hash and move
|
||||
on. Deriving names from link text is worse still: free-form, frequently duplicated, and
|
||||
sometimes absent.
|
||||
|
||||
## Extract the text once you have the bytes
|
||||
|
||||
With the file on disk, or just the bytes still in memory, a PDF library turns the
|
||||
pages into text. `pypdf` is a common choice for this:
|
||||
|
||||
```python
|
||||
from pypdf import PdfReader
|
||||
|
||||
reader = PdfReader("pdfs/report.pdf")
|
||||
text = "\n".join(page.extract_text() or "" for page in reader.pages)
|
||||
```
|
||||
|
||||
Run against the file fetched above, that returned one page and the exact string the PDF
|
||||
was built with. pypdf describes itself on PyPI as "a pure-python PDF library capable of
|
||||
splitting, merging, cropping, and transforming PDF files", and `extract_text()` on a page
|
||||
object is its own documented example. A file returning an empty string from
|
||||
`extract_text()` on every page usually has no real text layer: a scanned image saved
|
||||
as a PDF rather than text ever typeset. That case needs OCR, a different tool
|
||||
entirely and outside what a text-extraction library does.
|
||||
|
||||
## When the link opens a viewer tab instead of downloading anything
|
||||
|
||||
Some PDF links, especially ones without a download attribute, open Firefox's
|
||||
built-in viewer in a new tab rather than triggering a download at all. That is a
|
||||
distinct problem, catching the popup and then getting real bytes out from under the
|
||||
viewer, and it has [its own page](how-to-handle-pdf-opens-new-tab-playwright.md)
|
||||
rather than a paragraph here.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Bulk PDF collection is finding, fetching and reading, and each step fails for a
|
||||
different reason if skipped. Confirm a link is really a PDF by content type rather
|
||||
than URL shape, fetch it through the page's own request context so a login or a bot
|
||||
check does not refuse a stranger, name the result deterministically, and hand the
|
||||
bytes to a PDF library once they are on disk. The one case deferred entirely here, a
|
||||
PDF opening in Firefox's own viewer tab, has a dedicated page of its own.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**How do I download all PDF links from a page with Playwright?** Collect every
|
||||
anchor's `href`, fetch each through `page.request`, and keep the ones whose response
|
||||
`content-type` is `application/pdf`. That catches redirectors and disguised
|
||||
query-string links a `.pdf` check would miss.
|
||||
|
||||
**Why does requests.get return HTML instead of the PDF?** Either the PDF needs a
|
||||
login the separate client never presents, or a bot check on the handshake and
|
||||
headers is refusing a client that is not a real browser.
|
||||
|
||||
**How do I get a PDF that requires being logged in?** Fetch it with `page.request`
|
||||
after signing in. The request context shares the browser's cookie jar automatically,
|
||||
so the session carries over without copying anything by hand.
|
||||
|
||||
**How do I name downloaded PDFs so reruns do not duplicate them?** Hash the source
|
||||
URL into the filename, or read the `filename` parameter off `Content-Disposition` if
|
||||
the server sets one.
|
||||
|
||||
**What if the PDF opens in a viewer tab instead of downloading?** That is a separate
|
||||
situation, catching the new tab and pulling real bytes out from under Firefox's
|
||||
viewer, covered on its own page.
|
||||
|
||||
**See also:** [how to handle a PDF that opens in a new
|
||||
tab](how-to-handle-pdf-opens-new-tab-playwright.md), [how to download files with
|
||||
Playwright](how-to-download-files-playwright.md), and [reading and setting cookies in
|
||||
a Playwright context](read-set-cookies-playwright-context.md).
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Downloads, https://playwright.dev/python/docs/downloads - `expect_download`
|
||||
and `save_as`, the route that applies when the server sends the file as an attachment.
|
||||
Read 5 September 2026.
|
||||
- pypdf on PyPI, https://pypi.org/project/pypdf/ - the quoted project description and the
|
||||
`PdfReader` / `extract_text()` example. Read 5 September 2026, version 6.17.0.
|
||||
- Our own measurement, 5 September 2026, on a locally served page and two generated PDFs:
|
||||
in-page `fetch` returned 200 and `application/pdf`; `page.goto()` on a PDF returned no
|
||||
response object because Firefox's viewer took over; `expect_download` timed out on a
|
||||
plain link; the out-of-page request API is refused by this engine; and pypdf read the
|
||||
text back from the fetched bytes.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
a Firefox patched at the C++ level driven by stock Playwright. Most of the PDF links
|
||||
that ever gave me trouble were not broken; they just were not PDFs yet when I fetched
|
||||
them.*
|
||||
@@ -10,7 +10,7 @@ nav_order: 139
|
||||
# How to scrape live sports scores with Playwright
|
||||
|
||||
To scrape live sports scores with Playwright, treat the score as one field inside a
|
||||
larger, time-stamped update rather than a number you read off the page: capture match
|
||||
larger, time-stamped update instead of a number you read off the page: capture match
|
||||
state alongside the score so a 0-0 reading means something, timestamp each update against
|
||||
the feed's own clock instead of your scrape time, allow the score to decrease after a
|
||||
video review instead of rejecting it as bad data, and match commentary events to the
|
||||
@@ -23,7 +23,7 @@ This is a narrower problem than reading a scoreboard once or pulling post-match
|
||||
covers reading the feed transport itself, switching parsers between live and finished
|
||||
formats, and holding a long session without tripping a rate check. This page assumes you
|
||||
have already solved that part and asks the harder question underneath it: once you are
|
||||
receiving updates, what makes an in-play score reading correct rather than merely recent.
|
||||
receiving updates, what makes an in-play score reading correct, not merely recent.
|
||||
|
||||
## Why a live score is a moving target, not a snapshot
|
||||
|
||||
@@ -184,7 +184,7 @@ it were a real overturned goal.
|
||||
## Match commentary events to their own clock, not your scrape time
|
||||
|
||||
Goals, cards and substitutions usually arrive on a separate timestamped stream from the
|
||||
scoreboard number itself, an event feed rather than the score endpoint. Each event
|
||||
scoreboard number itself, an event feed instead of the score endpoint. Each event
|
||||
carries its own minute, and that minute is what ties it to the score, not whatever time
|
||||
your scraper happened to read either stream.
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ nav_order: 107
|
||||
# How to scrape multi-select facet filters with Playwright
|
||||
|
||||
To scrape multi-select facet filters with Playwright, expand every "show more" control
|
||||
before reading a group, wait for the facet response rather than for the URL to change,
|
||||
before reading a group, wait for the facet response, not for the URL to change,
|
||||
write the resulting URL into every row you store, and crawl one facet group at a time
|
||||
against the unfiltered base instead of enumerating combinations, then reconcile each group
|
||||
against the base total.
|
||||
@@ -102,7 +102,7 @@ from "this site has no such value" from "it was behind a show-more you did not e
|
||||
Absence is not evidence, and a coverage report built on it will claim gaps that are
|
||||
artifacts of the read.
|
||||
|
||||
Read the flag explicitly rather than asking whether the row is clickable. A `disabled`
|
||||
Read the flag explicitly instead of asking whether the row is clickable. A `disabled`
|
||||
attribute on a `<li>` or an `<a>` is ignored by the browser, since only native controls
|
||||
like `input` and `button` can be disabled that way, so such a row stays clickable. What
|
||||
means something is `aria-disabled` on the row and the `disabled` property on the input
|
||||
@@ -117,7 +117,7 @@ with the new state's URL: every row looks plausible and the whole table is shift
|
||||
|
||||
Wait on the response instead, and better still read it, since the payload usually carries
|
||||
the new counts and skipping the DOM removes the repaint race completely. Capturing the
|
||||
request rather than the repainted markup is a habit worth having generally, and
|
||||
request instead of the repainted markup is a habit worth having generally, and
|
||||
[capturing XHR and API responses](how-to-capture-xhr-api-responses-playwright.md) covers
|
||||
the hooks.
|
||||
|
||||
@@ -247,7 +247,7 @@ def reconcile(rows, base_total):
|
||||
Here is where the approach stops helping. One group at a time gives marginals, never the
|
||||
joint distribution, so "how many blue and large" needs that exact state visited. Pairs are
|
||||
quadratic and usually affordable, triples usually are not, so pick the pairs you need
|
||||
rather than generating them. A capped result set forces the same targeted split, and the
|
||||
instead of generating them. A capped result set forces the same targeted split, and the
|
||||
[paginated pages](how-to-scrape-paginated-pages-playwright.md) mechanics apply to each
|
||||
slice unchanged.
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ nav_order: 129
|
||||
To scrape newsletter archives with Playwright, page through the archive index until a
|
||||
page comes back empty or its first item repeats the item from the page before, since
|
||||
these archives almost never print a total to stop at, read each issue from the hosted
|
||||
rendering the archive actually serves rather than assuming it matches what a subscriber
|
||||
rendering the archive actually serves instead of assuming it matches what a subscriber
|
||||
got by email, and treat the date shown on the archive as the date the issue was added to
|
||||
that archive, not the date it was sent, until you confirm the two agree.
|
||||
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
---
|
||||
title: "How to scrape numbers rendered as images with Playwright"
|
||||
description: "Read prices and figures a site renders as images or sprites with Playwright: recover the value from the markup the page already carries before reaching for pixels, and know when to stop."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 168
|
||||
---
|
||||
|
||||
|
||||
# How to scrape numbers rendered as images with Playwright
|
||||
|
||||
When a site renders a number as an image, look for the value in the **markup around the
|
||||
image** before trying to read pixels. Sites that do this almost always leave the number
|
||||
somewhere accessible, because a figure that no screen reader can announce is a figure that
|
||||
fails accessibility law in most of their markets.
|
||||
|
||||
That is the practical order of attack, and it resolves the majority of cases in a few
|
||||
lines. Optical recognition is the last resort, not the first, and this page is partly about
|
||||
recognising when the right answer is to stop.
|
||||
|
||||
## Look in the accessible layer first
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
PROBE = """
|
||||
(sel) => {
|
||||
const el = document.querySelector(sel);
|
||||
if (!el) return null;
|
||||
const img = el.tagName === 'IMG' ? el : el.querySelector('img');
|
||||
return {
|
||||
alt: img ? img.getAttribute('alt') : null,
|
||||
title: el.getAttribute('title'),
|
||||
ariaLabel: el.getAttribute('aria-label'),
|
||||
dataset: Object.assign({}, el.dataset),
|
||||
srOnly: el.querySelector('.sr-only, .visually-hidden')?.textContent.trim() || null,
|
||||
describedBy: (() => {
|
||||
const id = el.getAttribute('aria-describedby');
|
||||
return id ? document.getElementById(id)?.textContent.trim() : null;
|
||||
})(),
|
||||
};
|
||||
}
|
||||
"""
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example.com/product/1234")
|
||||
found = page.evaluate(PROBE, ".price-image")
|
||||
```
|
||||
|
||||
In practice one of `alt`, `aria-label`, a `data-` attribute or a visually hidden span
|
||||
carries the digits. Check all of them instead of the first, because which one is used
|
||||
varies by framework and sometimes within a single page.
|
||||
|
||||
## Then check whether it is a sprite, not an image of a number
|
||||
|
||||
A common technique renders each digit as a background-position offset into one sprite
|
||||
image. The number is then recoverable arithmetically, with no recognition involved:
|
||||
|
||||
```python
|
||||
OFFSETS = """
|
||||
() => Array.from(document.querySelectorAll('.price .digit')).map(d => {
|
||||
const s = getComputedStyle(d);
|
||||
return { x: s.backgroundPositionX, y: s.backgroundPositionY, w: s.width };
|
||||
})
|
||||
"""
|
||||
digits = page.evaluate(OFFSETS)
|
||||
```
|
||||
|
||||
Each distinct offset maps to one digit. Calibrate once on a page where you know the value
|
||||
from elsewhere, build the offset-to-digit map, and every other page on that site decodes
|
||||
exactly. This is more reliable than recognition because it is a lookup, and it breaks
|
||||
loudly, not silently when the site changes the sprite.
|
||||
|
||||
Be aware that the mapping is often deliberately shuffled per session or per page load, and
|
||||
in that case it is a defence instead of an artefact. That distinction matters for what you
|
||||
do next.
|
||||
|
||||
## Custom fonts with remapped glyphs
|
||||
|
||||
A third variant ships a font where the glyph for "7" draws a 3. The DOM text is then
|
||||
misleading, not absent: you read a number and it is wrong, with no error anywhere.
|
||||
|
||||
The tell is a page-specific `@font-face` with an obfuscated family name applied to exactly
|
||||
the elements carrying figures. If you find one, the DOM text cannot be trusted for those
|
||||
elements, and you either decode the font's character map or you stop. Reading the text and
|
||||
hoping is the one option that produces a database full of confidently wrong numbers.
|
||||
|
||||
## If you do render, render the element and nothing else
|
||||
|
||||
Where the value genuinely exists only as pixels and you have a legitimate reason to read it,
|
||||
capture the element rather than the page:
|
||||
|
||||
```python
|
||||
element = page.query_selector(".price-image")
|
||||
element.screenshot(path="price.png")
|
||||
```
|
||||
|
||||
An element screenshot is smaller, deterministic and much easier to feed to recognition than
|
||||
a full page. The general capture mechanics, including the traps around lazy content and
|
||||
scroll position, are in
|
||||
[taking full page screenshots](how-to-take-full-page-screenshots-playwright.md).
|
||||
|
||||
⛔ **Do not detect change by hashing the PNG. We measured this and it nearly produced a
|
||||
false conclusion.** Building a canvas comparison bench, we hashed the PNG bytes of each
|
||||
capture and got **three different md5 values across three runs of the same page**, on
|
||||
unmodified retail Firefox. The obvious reading was that Firefox randomises canvas output
|
||||
by itself.
|
||||
|
||||
It was wrong. The three PNG files had **identical byte length** and differing content: the
|
||||
variation was encoder metadata, not pixels. Decoding to a pixel array and comparing that
|
||||
instead, all three runs were **stable**, and so were the other two arms of the bench.
|
||||
|
||||
The practical rule that falls out of it, for any pipeline that watches a rendered number
|
||||
for change:
|
||||
|
||||
```python
|
||||
from PIL import Image
|
||||
import hashlib, io
|
||||
|
||||
def pixel_digest(png_bytes):
|
||||
img = Image.open(io.BytesIO(png_bytes)).convert("RGB")
|
||||
return hashlib.sha256(img.tobytes()).hexdigest() # pixels, not the file
|
||||
```
|
||||
|
||||
A file hash answers "are these two files identical", which is not the question. The
|
||||
question is whether the image changed, and only the decoded pixels answer that. The same
|
||||
trap appears whenever a screenshot is used as evidence rather than as a picture, which is
|
||||
also why
|
||||
[a screenshot that comes back as noise](playwright-screenshot-returns-noise.md) is worth
|
||||
recognising as its own failure rather than as a changed page.
|
||||
|
||||
Then treat the recognised value as a measurement with an error rate, not as a fact. Store
|
||||
the image path or hash next to the number so a suspicious row can be checked by a human,
|
||||
and set a confidence threshold below which you record a null rather than a guess.
|
||||
|
||||
## When to stop, and why that is a real answer
|
||||
|
||||
Sprite shuffling, per-session glyph remapping and image-only figures with no accessible
|
||||
label are all deliberate anti-extraction measures. When you meet the deliberate version,
|
||||
the useful question is whether you have a relationship with the site that entitles you to
|
||||
the data, such as a contract, an API, or a published export.
|
||||
|
||||
There is a related honesty point that runs through this whole corpus. A browser that
|
||||
behaves like a real browser gets past defences aimed at things that are not browsers, and
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md) covers where
|
||||
that line sits. It does not, and should not, extend to defeating a measure whose only
|
||||
purpose is to say no to bulk extraction of that specific field.
|
||||
|
||||
The number rendered as an image is usually a price. Prices are also usually available in a
|
||||
feed, a partner API, or a structured markup block the same page emits for search engines,
|
||||
which is worth checking before any of the above:
|
||||
[extracting JSON-LD structured data](how-to-extract-json-ld-structured-data-playwright.md)
|
||||
takes about a minute to rule in or out.
|
||||
|
||||
## A complete probe that tries the cheap routes in order
|
||||
|
||||
```python
|
||||
import json, re, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
def recover_number(page, selector):
|
||||
"""Return (value, method) using the cheapest route that works."""
|
||||
ld = page.eval_on_selector_all(
|
||||
"script[type='application/ld+json']",
|
||||
"els => els.map(e => e.textContent)",
|
||||
)
|
||||
for blob in ld:
|
||||
try:
|
||||
data = json.loads(blob)
|
||||
except Exception:
|
||||
continue
|
||||
offers = (data.get("offers") if isinstance(data, dict) else None) or {}
|
||||
if isinstance(offers, dict) and offers.get("price"):
|
||||
return offers["price"], "json-ld"
|
||||
|
||||
probe = page.evaluate(PROBE, selector)
|
||||
if probe:
|
||||
for field in ("ariaLabel", "alt", "title", "srOnly", "describedBy"):
|
||||
text = probe.get(field)
|
||||
if text and re.search(r"\d", text):
|
||||
return text.strip(), f"accessible:{field}"
|
||||
for k, v in (probe.get("dataset") or {}).items():
|
||||
if re.fullmatch(r"[\d.,]+", str(v)):
|
||||
return v, f"dataset:{k}"
|
||||
|
||||
digits = page.evaluate(OFFSETS)
|
||||
if digits and all(d.get("x") for d in digits):
|
||||
return decode_sprite(digits), "sprite"
|
||||
|
||||
return None, "unresolved"
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("prices.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
for url in product_urls:
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
page.wait_for_selector(".price-image, .price", timeout=20000)
|
||||
value, method = recover_number(page, ".price-image")
|
||||
out.write(json.dumps({"url": url, "value": value, "method": method,
|
||||
"observed_at": time.time()}, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(2000)
|
||||
```
|
||||
|
||||
Recording `method` on every row is the part that makes this maintainable. When a site
|
||||
changes its rendering, the method column shows you exactly which pages moved from
|
||||
`accessible:alt` to `unresolved`, which is a far better signal than a column of nulls
|
||||
appearing with no explanation.
|
||||
|
||||
## Why this technique exists, and what that implies
|
||||
|
||||
Rendering a number as an image is expensive: it costs the site accessibility, translation,
|
||||
selectable text and search visibility for that field. Sites accept those costs for two
|
||||
different reasons, and the reason determines what you should do next.
|
||||
|
||||
**Legacy or laziness.** A price baked into a promotional banner, a figure in a chart image,
|
||||
a table exported as a picture. There is no intent to stop anyone, the accessible label is
|
||||
usually present, and reading it is ordinary extraction.
|
||||
|
||||
**Deliberate anti-extraction.** Per-session sprite shuffling, glyph-remapped fonts,
|
||||
canvas-drawn digits with no accessible layer. These cost the site real money in
|
||||
accessibility compliance, which is how you can tell the choice was intentional.
|
||||
|
||||
The second case is the one worth naming clearly. This corpus is about making a browser
|
||||
behave like a browser so that defences aimed at non-browsers stop misfiring on you. That is
|
||||
a different thing from defeating a control whose only purpose is to prevent bulk
|
||||
extraction of one specific field, and the honest response there is to ask whether you have
|
||||
a relationship with the site that entitles you to the data: a contract, an API, a partner
|
||||
feed. The reasoning around that line runs through
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## If you do recognise, treat the output as a measurement
|
||||
|
||||
Recognition output is not a fact, and the schema should say so:
|
||||
|
||||
| field | note |
|
||||
|---|---|
|
||||
| `value` | null when confidence is below your threshold, never a guess |
|
||||
| `method` | `json-ld`, `accessible:alt`, `sprite`, `ocr`, `unresolved` |
|
||||
| `confidence` | only present for `ocr` |
|
||||
| `evidence` | path or hash of the element screenshot, for a human to check |
|
||||
|
||||
A null with an image to look at is a workable row. A confidently wrong price is not, and it
|
||||
is the outcome that a pipeline without a threshold produces by default. Set the threshold
|
||||
high enough that the nulls annoy you, then fix the extraction rather than lowering the bar,
|
||||
because the alternative is a dataset whose errors are invisible and whose consumers have no
|
||||
way to find them.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Where do I look before trying to read pixels?** The accessible layer. In practice
|
||||
one of `alt`, `aria-label`, a `data-` attribute or a visually hidden span carries the
|
||||
digits, because the site still has to be readable by a screen reader.
|
||||
|
||||
**The image is one file for the whole number. Now what?** Check whether it is a
|
||||
sprite. A common technique renders each digit as a background offset into a single
|
||||
image, and the offsets decode to digits without any recognition.
|
||||
|
||||
**The DOM text is there but wrong.** That is the third variant: a custom font whose
|
||||
glyph for one digit draws another. The text is misleading instead of missing, which is
|
||||
worse, because nothing looks broken.
|
||||
|
||||
**When should I give up?** Sooner than feels comfortable, and that is a real answer.
|
||||
Sprite shuffling, per-session glyph remapping and an image with no accessible label
|
||||
are deliberate, and recognition output is a measurement with an error rate, not a
|
||||
fact.
|
||||
|
||||
**See also:** [How to take full-page screenshots with
|
||||
Playwright](how-to-take-full-page-screenshots-playwright.md), [How to extract JSON-LD
|
||||
structured data with
|
||||
Playwright](how-to-extract-json-ld-structured-data-playwright.md), [How to scrape
|
||||
without getting blocked](how-to-scrape-without-getting-blocked.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- MDN, `aria-label`,
|
||||
https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-label
|
||||
- the attribute that most often carries the digits a site renders as an image,
|
||||
checked as the first place this page looks.
|
||||
- Playwright, Locators, https://playwright.dev/python/docs/api/class-locator - reading
|
||||
attributes and taking an element screenshot scoped to one node.
|
||||
@@ -13,7 +13,7 @@ To scrape nutrition labels with Playwright, attach a basis to every number befor
|
||||
store it: map each column header to per 100 g, per serving or per package, split the
|
||||
serving size into a household measure and a metric one, keep kilojoules and kilocalories
|
||||
in separate fields, preserve the less-than qualifier instead of parsing it to zero, and
|
||||
record an image-only panel as unextractable rather than writing empty rows.
|
||||
record an image-only panel as unextractable instead of writing empty rows.
|
||||
|
||||
A nutrition panel is a small grid, and reading the grid is the easy part. The hard part is
|
||||
that almost every number on it means nothing on its own. `12` is not a fact. Twelve grams
|
||||
@@ -36,7 +36,7 @@ serving size, which a scraper that dropped the basis has almost always dropped t
|
||||
On a product page the panel is usually collapsed behind a "Nutrition" accordion or a tab,
|
||||
so it sits in the DOM unrendered, or it does not exist until the header is clicked.
|
||||
[Scraping accordion and tab content](how-to-scrape-accordion-and-tab-content-playwright.md)
|
||||
covers opening it and waiting for the panel rather than for the click.
|
||||
covers opening it and waiting for the panel, not for the click.
|
||||
|
||||
The basis lives in the header row and never in the cell. Read the header first, classify
|
||||
each column, and refuse the panel when nothing classifies. Refusing is the useful
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
---
|
||||
title: "How to scrape package download statistics with Playwright"
|
||||
description: "Scrape package download counts with Playwright: take the series behind the chart rather than the rendered chart, keep the mirror and CI caveats with the numbers, and prefer the published dataset where one exists."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 163
|
||||
---
|
||||
|
||||
|
||||
# How to scrape package download statistics with Playwright
|
||||
|
||||
To scrape download statistics, take the **series the chart is drawing**, not the chart.
|
||||
Every registry dashboard renders its graph from a JSON response, and that response has the
|
||||
per-day numbers at full precision, already aligned to dates, without the rounding and
|
||||
smoothing the picture applies.
|
||||
|
||||
The second point matters more than the technique: a download count is not a user count.
|
||||
Mirrors, CI runs, container builds and caching proxies all appear as downloads, and on
|
||||
some packages they are the majority. A number captured without that caveat attached will
|
||||
be read as adoption by whoever sees it next, including you in six months.
|
||||
|
||||
This page covers taking the series, the caveats that belong with it, and the case for not
|
||||
scraping at all.
|
||||
|
||||
## First, check whether the data is published
|
||||
|
||||
Several registries publish their download data as a dataset or an endpoint, which is
|
||||
faster, complete, and does not require a browser. That is the correct first move, and it
|
||||
takes one look at the registry's documentation.
|
||||
|
||||
Where a public dataset exists, use it and stop reading here. This page is for the case
|
||||
where the numbers exist only behind a dashboard.
|
||||
|
||||
## Take the response, not the rendering
|
||||
|
||||
```python
|
||||
import time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
series = []
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
|
||||
def on_response(response):
|
||||
url = response.url
|
||||
if any(k in url for k in ("/downloads", "/stats", "/metrics")):
|
||||
try:
|
||||
series.append({"url": url, "at": time.time(), "body": response.json()})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
page.on("response", on_response)
|
||||
page.goto("https://registry.example.com/package/some-package")
|
||||
page.wait_for_selector("canvas, svg.chart")
|
||||
page.wait_for_timeout(2500)
|
||||
```
|
||||
|
||||
The request usually carries the window as parameters, which is the handle for getting more
|
||||
than the default view:
|
||||
|
||||
```python
|
||||
page.goto("https://registry.example.com/package/some-package?range=12m&interval=day")
|
||||
```
|
||||
|
||||
Change the range in the interface and watch which parameter moves, rather than guessing
|
||||
parameter names. The general mechanics, including the ordering trap where the response
|
||||
arrives before your listener is attached, are in
|
||||
[capturing XHR and API responses](how-to-capture-xhr-api-responses-playwright.md).
|
||||
|
||||
## When the numbers really are only in the picture
|
||||
|
||||
Some dashboards render server-side to an image, or draw to a canvas with no JSON behind
|
||||
it. Read the values from the accessible layer before reaching for pixels:
|
||||
|
||||
```python
|
||||
points = page.eval_on_selector_all(
|
||||
"svg.chart [role='graphics-symbol'], svg.chart .datapoint",
|
||||
"els => els.map(e => ({ label: e.getAttribute('aria-label'), value: e.dataset.value }))",
|
||||
)
|
||||
```
|
||||
|
||||
Charts built for accessibility carry the values in attributes, and reading them is exact
|
||||
where reading pixels is not. Where that fails too, the approach and its limits are in
|
||||
[extracting data from canvas charts](how-to-extract-data-from-canvas-charts-playwright.md).
|
||||
|
||||
## Keep the caveats in the row, not in your head
|
||||
|
||||
Store the qualifiers the registry itself publishes, because they change what the number
|
||||
means:
|
||||
|
||||
```python
|
||||
row = {
|
||||
"package": "some-package",
|
||||
"date": "2026-09-06",
|
||||
"downloads": 18432,
|
||||
"counts_mirrors": None, # unknown unless the registry says
|
||||
"source": "registry dashboard",
|
||||
"captured_at": time.time(),
|
||||
}
|
||||
```
|
||||
|
||||
Three specific distortions are worth a column each where the registry tells you:
|
||||
|
||||
- **Mirrors and proxies.** A single corporate proxy can multiply or divide the count.
|
||||
- **CI traffic.** A popular library's weekday-versus-weekend pattern is often CI, not
|
||||
people, and it is visible as a flat weekly cycle in the series.
|
||||
- **Version splits.** Total downloads across versions hide that most traffic is an old
|
||||
pinned release, which is usually the interesting fact.
|
||||
|
||||
Where the dashboard offers a per-version breakdown, take it. Total-only series answer
|
||||
almost no question worth asking.
|
||||
|
||||
## Comparing packages is where this goes wrong
|
||||
|
||||
The tempting use is a comparison, and it is the least reliable one. Two packages with the
|
||||
same headline count can differ by an order of magnitude in real users, because one is a
|
||||
transitive dependency of something popular and the other is installed deliberately.
|
||||
|
||||
If you make the comparison anyway, at minimum compare the same window, the same interval
|
||||
and the same registry, and say in the output that the number counts requests. That is the
|
||||
same honesty a
|
||||
[realness-first mindset](how-to-scrape-without-getting-blocked.md) asks for elsewhere:
|
||||
report what you measured, not what you hope it means.
|
||||
|
||||
## Store the series long, refresh daily
|
||||
|
||||
One row per package per day per version, appended. Registries revise recent days for
|
||||
several days after the fact, so re-fetch a trailing window rather than only yesterday:
|
||||
|
||||
```python
|
||||
for day in last_n_days(10):
|
||||
upsert(package, day, value_for(day))
|
||||
```
|
||||
|
||||
Ten days of overlap costs nothing and quietly repairs the revisions. Daily is the right
|
||||
cadence, the pacing rules in
|
||||
[rate limiting your own scraper](how-to-rate-limit-your-scraper-playwright.md) apply, and
|
||||
[JSON Lines](how-to-scrape-to-json-lines-playwright.md) is a good fit for an append-only
|
||||
series you will reprocess later.
|
||||
|
||||
## A complete daily collector
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
PACKAGES = ["some-package", "another-package"]
|
||||
|
||||
def collect(page, package):
|
||||
captured = []
|
||||
|
||||
def on_response(response):
|
||||
if any(k in response.url for k in ("/downloads", "/stats", "/metrics")):
|
||||
try:
|
||||
captured.append({"url": response.url, "body": response.json()})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
page.on("response", on_response)
|
||||
page.goto(f"https://registry.example.com/package/{package}?range=12m&interval=day",
|
||||
wait_until="domcontentloaded")
|
||||
page.wait_for_selector("canvas, svg.chart", timeout=20000)
|
||||
page.wait_for_timeout(2500)
|
||||
page.remove_listener("response", on_response)
|
||||
|
||||
if not captured: # no JSON: fall back to the accessible layer
|
||||
points = page.eval_on_selector_all(
|
||||
"svg.chart [role='graphics-symbol'], svg.chart .datapoint",
|
||||
"els => els.map(e => ({label: e.getAttribute('aria-label'), value: e.dataset.value}))",
|
||||
)
|
||||
return [{"package": package, "source": "accessible-layer", "points": points}]
|
||||
return [{"package": package, "source": "json", **c} for c in captured]
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("downloads.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
for package in PACKAGES:
|
||||
for record in collect(page, package):
|
||||
record["observed_at"] = time.time()
|
||||
out.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(4000)
|
||||
```
|
||||
|
||||
Recording `source` alongside the numbers is what keeps a mixed dataset honest. A series
|
||||
built partly from the JSON endpoint and partly from chart labels has two different
|
||||
precisions in one column, and the only way to notice later is if the row says which it was.
|
||||
|
||||
## Why the browser is needed for a number that looks public
|
||||
|
||||
Download counts feel like open data, and the dashboard usually is. Two things still push
|
||||
this into browser territory.
|
||||
|
||||
**The series endpoint expects the page.** Many registries check the referrer, a session
|
||||
cookie or a token minted by the page before serving the JSON. A direct request for the
|
||||
same URL returns an error or an empty series, which is why the code lets the page make the
|
||||
request and captures the response rather than replaying the URL.
|
||||
|
||||
**Degradation is silent and looks like a quiet week.** Under protection the chart renders
|
||||
with no data and the page looks fine. A collector that stores whatever arrived writes zeros,
|
||||
and zeros in a download series are indistinguishable from a real collapse in usage. Guard
|
||||
positively:
|
||||
|
||||
```python
|
||||
if record["source"] == "json":
|
||||
series = record["body"].get("downloads") or record["body"].get("data") or []
|
||||
if not series:
|
||||
raise RuntimeError("empty series returned: failed read, not a quiet week")
|
||||
```
|
||||
|
||||
The order to debug that, cheapest first, is in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md). And the point
|
||||
worth repeating from the top of this page: if the registry publishes the data as a dataset,
|
||||
none of this is necessary, and checking takes a minute.
|
||||
|
||||
## The schema, and the comparison it refuses to make easy
|
||||
|
||||
One row per package, version, date and observation:
|
||||
|
||||
| field | note |
|
||||
|---|---|
|
||||
| `package`, `version` | version is null only when the registry offers no breakdown |
|
||||
| `date` | the registry's day, not yours |
|
||||
| `downloads` | the count as served |
|
||||
| `source` | `json` or `accessible-layer` |
|
||||
| `observed_at` | so a revision is visible as two rows for one day |
|
||||
|
||||
Keeping the observation timestamp separate from the data date is what makes revisions
|
||||
detectable: the same `date` collected twice with different `downloads` is a registry
|
||||
correction, and that is a fact worth having rather than an inconsistency to overwrite.
|
||||
|
||||
The comparison this schema deliberately does not make easy is the one people want most:
|
||||
package A against package B. You can write the query, and the answer will be misleading
|
||||
unless both series carry the same window, the same interval and the same caveats about
|
||||
mirrors and continuous integration. Keeping `version` in the key at least surfaces the
|
||||
usual explanation, which is that most of a popular library's traffic is one old pinned
|
||||
release being pulled by machines.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Do I need a browser for download counts at all?** Often not, and that is the first
|
||||
thing to check. Several registries publish the numbers as a dataset or an endpoint,
|
||||
which is faster and more complete than any dashboard. Reach for a browser when the
|
||||
dashboard is the only published form.
|
||||
|
||||
**Should I read the chart or the request behind it?** The request. It usually carries
|
||||
the window as parameters, which is the handle for getting more than the dashboard
|
||||
chooses to draw.
|
||||
|
||||
**Why do recent days keep changing?** Registries revise the last few days as mirrors
|
||||
and logs settle. Append one row per day per observation instead of overwriting, or the
|
||||
revisions erase themselves.
|
||||
|
||||
**Can I compare two packages by download count?** This is the tempting use and the
|
||||
least reliable one. The same headline number can be made of very different traffic, so
|
||||
keep the qualifiers the registry publishes in the row itself, where they stay attached
|
||||
to the number they qualify.
|
||||
|
||||
**See also:** [How to capture XHR and API responses in
|
||||
Playwright](how-to-capture-xhr-api-responses-playwright.md), [Extract data from canvas
|
||||
charts with Playwright](how-to-extract-data-from-canvas-charts-playwright.md), [How to
|
||||
scrape to JSON Lines with Playwright](how-to-scrape-to-json-lines-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- PyPI, Stats API, https://docs.pypi.org/api/stats/ - an example of a registry
|
||||
publishing download data directly, checked for the first step this page recommends,
|
||||
which is to look for the dataset before opening a browser.
|
||||
- Playwright, Network, https://playwright.dev/python/docs/network -
|
||||
`page.expect_response()`, checked for taking the dashboard's own request instead of
|
||||
its rendering.
|
||||
@@ -0,0 +1,273 @@
|
||||
---
|
||||
title: "How to scrape package tracking status with Playwright"
|
||||
description: "Scrape parcel tracking with Playwright: capture the event timeline instead of the headline status, keep the carrier's own wording, and poll on the shipment's clock instead of yours."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 155
|
||||
---
|
||||
|
||||
|
||||
# How to scrape package tracking status with Playwright
|
||||
|
||||
To scrape tracking, capture the **event timeline**, not the headline status. A
|
||||
tracking page shows one summary word at the top, and that word is a carrier's
|
||||
interpretation of a list of scans underneath it. The list is the data. The summary is a
|
||||
derived field you can always recompute, and it is the field carriers change the wording
|
||||
of without warning.
|
||||
|
||||
The second thing to get right is the polling interval. A parcel generates a handful of
|
||||
events over several days, so a tight poll produces thousands of identical reads and an
|
||||
obvious traffic signature, on endpoints that are unusually well monitored because they
|
||||
are a favourite target of abuse.
|
||||
|
||||
This page covers reading the timeline, keeping carrier vocabulary intact, and polling in
|
||||
a way that matches how shipments actually move.
|
||||
|
||||
## Read the timeline, one row per scan
|
||||
|
||||
Each scan is a timestamp, a location and a description. Capture all three:
|
||||
|
||||
```python
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
def timeline(page):
|
||||
events = []
|
||||
for row in page.query_selector_all(".tracking-event, li.event"):
|
||||
def text(sel):
|
||||
node = row.query_selector(sel)
|
||||
return node.inner_text().strip() if node else None
|
||||
events.append({
|
||||
"when_text": text(".event-date, time"),
|
||||
"where": text(".event-location"),
|
||||
"what": text(".event-description, .status-text"),
|
||||
})
|
||||
return events
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example-carrier.com/track?number=ABC123456789")
|
||||
page.wait_for_selector(".tracking-event, .not-found")
|
||||
events = timeline(page)
|
||||
```
|
||||
|
||||
Keep `when_text` as text at capture time. Carriers write dates in local formats, in the
|
||||
timezone of the scanning facility, sometimes without a year, and a parse that fails
|
||||
silently at capture puts a wrong timestamp in your database forever. Parse in a second
|
||||
pass where you can see what failed.
|
||||
|
||||
## Order is not guaranteed, and neither is stability
|
||||
|
||||
Two properties of these timelines surprise people. Events do not always arrive in order,
|
||||
because facilities upload in batches, so a scan from Tuesday can appear after one from
|
||||
Wednesday. And events are sometimes **revised**: a carrier can correct a location or drop
|
||||
a duplicate scan between two of your reads.
|
||||
|
||||
Treat the timeline as a set keyed on the event, not as an append-only log:
|
||||
|
||||
```python
|
||||
def merge(known, fresh):
|
||||
index = {(e["when_text"], e["what"], e["where"]): e for e in known}
|
||||
for e in fresh:
|
||||
index[(e["when_text"], e["what"], e["where"])] = e
|
||||
return sorted(index.values(), key=lambda e: e["when_text"] or "")
|
||||
```
|
||||
|
||||
If you also want to detect revisions rather than absorb them, keep each capture whole,
|
||||
with the time you took it, and diff captures later. That costs more rows and answers
|
||||
questions about carrier behaviour that a merged view erases.
|
||||
|
||||
## Keep the carrier's words, add your own status separately
|
||||
|
||||
Carriers use different vocabularies for the same physical event, and they change them.
|
||||
"Out for delivery", "With courier", "On vehicle for delivery" all mean the same thing at
|
||||
three carriers. Store the original string, then map it in a layer you control:
|
||||
|
||||
```python
|
||||
DELIVERED = {"delivered", "consegnato", "livre", "zugestellt"}
|
||||
|
||||
def is_delivered(event):
|
||||
return (event["what"] or "").strip().lower() in DELIVERED
|
||||
```
|
||||
|
||||
Keeping the mapping outside the capture means a new phrase costs you a line, rather than
|
||||
a re-scrape. It also keeps the honest fact that you are guessing at semantics visible in
|
||||
the code, instead of buried in a column called `status`.
|
||||
|
||||
## Poll on the shipment's clock
|
||||
|
||||
A parcel produces events at handoffs: collection, hub in, hub out, local depot, out for
|
||||
delivery, delivered. That is a handful of moments over days. Polling every minute is
|
||||
noise, and it looks exactly like the abuse these endpoints exist to resist.
|
||||
|
||||
A workable shape is an interval that widens when nothing changes and tightens near
|
||||
delivery:
|
||||
|
||||
```python
|
||||
def next_interval(events, last_seen):
|
||||
if not events:
|
||||
return 6 * 3600 # nothing yet: check rarely
|
||||
latest = events[-1]["what"] or ""
|
||||
if "out for delivery" in latest.lower():
|
||||
return 30 * 60 # the one phase worth watching closely
|
||||
if events == last_seen:
|
||||
return 4 * 3600
|
||||
return 60 * 60
|
||||
```
|
||||
|
||||
The general pacing rules, and why a self-imposed limit beats being told, are in
|
||||
[rate limiting your own scraper](how-to-rate-limit-your-scraper-playwright.md).
|
||||
|
||||
## Three traps worth knowing
|
||||
|
||||
**The number is entered, not in the URL.** Many carriers reject a URL with a tracking
|
||||
number in it unless the session has been through the form. Type it into the field and
|
||||
submit, the same way a person would.
|
||||
|
||||
**Not found and not yet scanned look identical.** A number that a carrier has never seen
|
||||
and one that was created but not collected both render as an empty page with a generic
|
||||
message. Capture the message text as a distinct outcome instead of writing an empty
|
||||
timeline.
|
||||
|
||||
**Consent walls and locale interstitials come first.** Especially on European carrier
|
||||
sites, the first visit is a consent dialog. Clear it once per session as in
|
||||
[handling cookie consent banners](how-to-handle-cookie-consent-banners-playwright.md).
|
||||
|
||||
## Track your own parcels
|
||||
|
||||
Tracking numbers are not personal data in themselves, but a timeline is a record of where
|
||||
someone's package went, and often where they live. Scrape numbers you have a reason to
|
||||
hold, keep the retention short, and do not enumerate. Guessing tracking numbers to see
|
||||
what comes back is the behaviour these endpoints are defended against, and it is the one
|
||||
use of this page that is not worth having.
|
||||
|
||||
## A complete watcher for a handful of parcels
|
||||
|
||||
```python
|
||||
import json, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
def read_tracking(page, number):
|
||||
page.goto("https://example-carrier.com/track")
|
||||
dismiss_consent(page)
|
||||
box = page.wait_for_selector("input[name='trackingNumber']")
|
||||
box.click()
|
||||
box.fill("")
|
||||
box.type(number, delay=70)
|
||||
page.keyboard.press("Enter")
|
||||
page.wait_for_selector(".tracking-event, .not-found, .no-info", timeout=25000)
|
||||
|
||||
if page.query_selector(".not-found") or page.query_selector(".no-info"):
|
||||
note = page.inner_text(".not-found, .no-info").strip()
|
||||
return {"number": number, "events": [], "carrier_note": note}
|
||||
return {"number": number, "events": timeline(page), "carrier_note": None}
|
||||
|
||||
def dismiss_consent(page):
|
||||
node = page.query_selector("#onetrust-accept-btn-handler, .consent-accept")
|
||||
if node:
|
||||
node.click()
|
||||
page.wait_for_timeout(400)
|
||||
|
||||
state = {}
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("parcels.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
while parcels_in_flight:
|
||||
for number in list(parcels_in_flight):
|
||||
result = read_tracking(page, number)
|
||||
merged = merge(state.get(number, []), result["events"])
|
||||
if merged != state.get(number):
|
||||
out.write(json.dumps({**result, "events": merged,
|
||||
"observed_at": time.time()}, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
state[number] = merged
|
||||
if merged and is_delivered(merged[-1]):
|
||||
parcels_in_flight.discard(number)
|
||||
page.wait_for_timeout(4000)
|
||||
time.sleep(next_interval(merged, state.get(number)))
|
||||
```
|
||||
|
||||
Writing only when the merged timeline changes is what keeps a multi-day watch from
|
||||
producing thousands of identical records. Dropping a parcel from the set once it is
|
||||
delivered is the other half: a delivered parcel never changes again, and continuing to
|
||||
poll it is pure noise on someone else's servers.
|
||||
|
||||
## Why carrier endpoints are among the best defended
|
||||
|
||||
Tracking pages are attacked constantly, because a valid tracking number is the entry
|
||||
point for parcel redirection fraud and for phishing that quotes a real shipment. The
|
||||
defences that result are aggressive, and three of them shape any honest scraper.
|
||||
|
||||
**Enumeration is the thing they watch for.** Sequential or high-volume lookups from one
|
||||
source are the signature, and they are met with a hard block rather than a challenge. This
|
||||
is the strongest practical argument for the rule above: hold numbers you have a reason to
|
||||
hold, and the traffic shape stops looking like the attack.
|
||||
|
||||
**A stripped client usually never sees a timeline.** The result region is fetched after the
|
||||
form commits, from an endpoint expecting the browser's context. Driving a real browser is
|
||||
what makes the request resolve, and a patched Firefox driven by stock Playwright presents
|
||||
the consistent handshake and fingerprint that a bare client cannot.
|
||||
|
||||
**Refusal is frequently disguised as "no information available".** That message is also the
|
||||
genuine response for a parcel not yet scanned, so the two are indistinguishable without
|
||||
care. Keep the carrier's exact wording and, when it appears for a number that previously
|
||||
had events, treat it as a suspicious read rather than a regression:
|
||||
|
||||
```python
|
||||
if not result["events"] and state.get(number):
|
||||
result["suspect"] = "timeline disappeared for a number that had events"
|
||||
```
|
||||
|
||||
The general debug order, cheapest check first, is in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## A schema that survives revisions
|
||||
|
||||
Two tables rather than one. A capture table holding the whole timeline per read, and a
|
||||
derived event table keyed on the event's own identity:
|
||||
|
||||
| table | key | holds |
|
||||
|---|---|---|
|
||||
| capture | `number`, `observed_at` | the full timeline as read, plus the carrier note |
|
||||
| event | `number`, `when_text`, `what`, `where` | one row per distinct scan, first and last seen |
|
||||
|
||||
Keeping the captures is what lets you detect a carrier revising or removing a scan, which
|
||||
a merged-only view silently absorbs. Keeping the derived events is what makes the ordinary
|
||||
question fast. The cost is duplication, and it is small compared with the alternative,
|
||||
which is a table that quietly rewrites its own history every time the carrier does.
|
||||
|
||||
For retention, delete captures once a parcel is delivered plus whatever window your use
|
||||
actually needs. A tracking archive is a movement record, and the honest default is to keep
|
||||
it only as long as it is answering a question.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why are the scan events out of order?** Because facilities upload in batches and a
|
||||
later scan can be written before an earlier one. Order is not guaranteed and neither
|
||||
is stability: a timeline can be revised between two reads, so store what you saw and
|
||||
when you saw it instead of assuming the last read is the truth.
|
||||
|
||||
**Should I map the carrier's wording to my own status?** Keep both. Carriers use
|
||||
different vocabularies for the same physical event and change them without notice, so
|
||||
the carrier's words are the record and your status is a derivation you can redo when
|
||||
the mapping turns out to be wrong.
|
||||
|
||||
**Why does the tracking page reject my URL?** Many carriers only accept a tracking
|
||||
number that was entered on the page, not one placed in the address bar. Type it into
|
||||
the field and submit the form.
|
||||
|
||||
**How often should I check a parcel?** On the shipment's clock. Parcels produce events
|
||||
at handoffs, a few times a day at most, so a tight poll loop buys nothing and is the
|
||||
easiest possible thing for a carrier to spot.
|
||||
|
||||
**See also:** [How to handle cookie consent banners in
|
||||
Playwright](how-to-handle-cookie-consent-banners-playwright.md), [How to rate limit
|
||||
your own Playwright scraper](how-to-rate-limit-your-scraper-playwright.md), [How to
|
||||
scrape without getting blocked](how-to-scrape-without-getting-blocked.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Input, https://playwright.dev/python/docs/input - `locator.fill()` and
|
||||
`press_sequentially()`, checked for entering a tracking number into a form that
|
||||
refuses a value placed in the URL.
|
||||
- This project's page on scraping without getting blocked, for the debug order when a
|
||||
read starts degrading instead of failing.
|
||||
@@ -0,0 +1,323 @@
|
||||
---
|
||||
title: "How to scrape parking rates with Playwright"
|
||||
description: "Scrape parking garage rates with Playwright: read the tariff table as duration bands, not prices, resolve the band an arrival time falls into, and keep the rules that override the table."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 150
|
||||
---
|
||||
|
||||
|
||||
# How to scrape parking rates with Playwright
|
||||
|
||||
To scrape parking rates, capture the tariff **table**, not a price: a garage does
|
||||
not have "a rate", it has duration bands whose boundaries move by day of week and time
|
||||
of arrival. Read every row as a triple of lower bound, upper bound and amount, record
|
||||
the day and time window each table applies to, and keep the override rules printed
|
||||
underneath it, because those are what decide the final amount more often than the rows
|
||||
above them.
|
||||
|
||||
The mistake that produces unusable data is scraping the number that the page shows you.
|
||||
A garage page usually renders one headline figure, chosen for a default stay that the
|
||||
site picked, and that figure changes if you arrive an hour later. Two runs a day apart
|
||||
then disagree, and nothing in the captured row explains why.
|
||||
|
||||
This page covers reading the band table without flattening it, handling the arrival
|
||||
time the page silently assumed, and the overrides that sit in small print and quietly
|
||||
outrank everything else.
|
||||
|
||||
## Read the bands, not the headline price
|
||||
|
||||
Capture every row of the tariff table with its bounds intact. The unit of data is the
|
||||
band, and a band without its bounds is a number with no meaning:
|
||||
|
||||
```python
|
||||
import re
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
DURATION = re.compile(
|
||||
r"(?P<lo>\d+(?:\.\d+)?)\s*(?P<lo_unit>min|minutes|hour|hours|hr|day|days)?"
|
||||
r"\s*(?:to|-|and)\s*"
|
||||
r"(?P<hi>\d+(?:\.\d+)?)\s*(?P<hi_unit>min|minutes|hour|hours|hr|day|days)",
|
||||
re.I,
|
||||
)
|
||||
|
||||
def to_minutes(value, unit):
|
||||
value = float(value)
|
||||
unit = (unit or "hour").lower()
|
||||
if unit.startswith("min"):
|
||||
return int(value)
|
||||
if unit.startswith(("hour", "hr")):
|
||||
return int(value * 60)
|
||||
return int(value * 60 * 24)
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://example.com/garages/central/rates")
|
||||
|
||||
bands = []
|
||||
for row in page.query_selector_all("table.rates tbody tr"):
|
||||
cells = [c.inner_text().strip() for c in row.query_selector_all("td")]
|
||||
if len(cells) < 2:
|
||||
continue
|
||||
m = DURATION.search(cells[0])
|
||||
if not m:
|
||||
continue # a footnote row, not a band
|
||||
bands.append({
|
||||
"from_minutes": to_minutes(m.group("lo"), m.group("lo_unit") or m.group("hi_unit")),
|
||||
"to_minutes": to_minutes(m.group("hi"), m.group("hi_unit")),
|
||||
"label": cells[0],
|
||||
"amount": cells[1],
|
||||
})
|
||||
```
|
||||
|
||||
Keep `label` alongside the parsed bounds. When a row parses in a way that later looks
|
||||
wrong, the original text is the only thing that lets you tell a bad regex from a strange
|
||||
tariff, and garages write these strings in every format there is.
|
||||
|
||||
## The table is scoped to a day and a time, and the page rarely says so twice
|
||||
|
||||
The same garage usually publishes several tables: weekday, weekend, event day, overnight.
|
||||
The page shows one at a time and switches between them with a control that does not
|
||||
change the URL. Scraping the visible table without recording which one it is produces
|
||||
rows that contradict each other for no visible reason.
|
||||
|
||||
Record the scope with the bands, and drive the control to collect the others:
|
||||
|
||||
```python
|
||||
tariffs = []
|
||||
for tab in page.query_selector_all("[role='tab'], .rate-tabs button"):
|
||||
scope = tab.inner_text().strip() # "Weekday", "Weekend", "Event"
|
||||
tab.click()
|
||||
page.wait_for_selector("table.rates tbody tr")
|
||||
tariffs.append({"scope": scope, "bands": read_bands(page)})
|
||||
```
|
||||
|
||||
Click the control instead of fetching a variant URL you guessed. The tab often triggers
|
||||
a request whose response the page merges into the table, and driving the real control is
|
||||
also the version that behaves like a visitor. The same reasoning applies to any
|
||||
[tabbed or accordion content](how-to-scrape-accordion-and-tab-content-playwright.md), where
|
||||
the hidden panels are frequently not in the DOM until something opens them.
|
||||
|
||||
## Resolve an arrival time instead of storing a spread
|
||||
|
||||
Once you have bands, a price is a function of two inputs: when the car arrives and how
|
||||
long it stays. Store the function, and compute prices at read time:
|
||||
|
||||
```python
|
||||
def price_for(tariff, arrival, minutes):
|
||||
"""arrival is a datetime, minutes an int. Returns the matching band."""
|
||||
scope = "Weekend" if arrival.weekday() >= 5 else "Weekday"
|
||||
table = next(t for t in tariff if t["scope"] == scope)
|
||||
for band in table["bands"]:
|
||||
if band["from_minutes"] <= minutes <= band["to_minutes"]:
|
||||
return band
|
||||
return table["bands"][-1] # over the top band: the daily maximum applies
|
||||
```
|
||||
|
||||
The fallback on the last line is not a detail. Most tariffs end with a maximum that
|
||||
covers everything beyond the final band, and a scraper that returns nothing for a
|
||||
fourteen hour stay is reporting an absence that the garage does not have.
|
||||
|
||||
## The small print outranks the table
|
||||
|
||||
Underneath the table sit the rules that decide the real amount: a daily maximum, a
|
||||
minimum charge, a grace period, a different rate after midnight, an early-bird rate that
|
||||
requires arriving before a cutoff. These are prose, not rows, and they routinely
|
||||
contradict the table above them.
|
||||
|
||||
Capture them verbatim instead of trying to parse them:
|
||||
|
||||
```python
|
||||
notes = [n.inner_text().strip()
|
||||
for n in page.query_selector_all(".rate-notes li, .rates-footnote")]
|
||||
```
|
||||
|
||||
Verbatim text is the honest form here. A parser that turns "maximum $28 per 24 hours,
|
||||
in and out privileges not included" into a number throws away the second clause, and the
|
||||
second clause is the one that makes the number wrong. Store the strings, resolve them
|
||||
when a human asks a question that needs them.
|
||||
|
||||
## Two practical traps
|
||||
|
||||
**The price appears after a date picker is filled.** Many operators only show rates once
|
||||
you enter arrival and departure. That is a form to drive, not a page to read, and it
|
||||
behaves like any other
|
||||
[multi-step wizard flow](how-to-scrape-multi-step-wizard-flow-playwright.md): fill it in
|
||||
order, wait for the result region, then read.
|
||||
|
||||
**Rates are location-scoped even on the same site.** A chain publishes the same page
|
||||
shell for every garage and fills the numbers per location, sometimes from your inferred
|
||||
position instead of the URL. If the figures change when the exit IP changes, the page is
|
||||
reading a location you did not set, and the fix is the one in
|
||||
[scraping geotargeted content](how-to-scrape-geotargeted-content-playwright.md).
|
||||
|
||||
## Collect politely, because these pages are cheap to overload
|
||||
|
||||
Parking operators run small sites. A run that walks every garage in a city at full speed
|
||||
is a visible load spike on infrastructure that was not built for it, and the block that
|
||||
follows is deserved rather than adversarial. Pace the run with
|
||||
[a rate limit you impose on yourself](how-to-rate-limit-your-scraper-playwright.md), and
|
||||
prefer one pass per day over a poll: tariffs change on the scale of months.
|
||||
|
||||
The result is a table of bands, plus scopes, plus notes. It is more data than a single
|
||||
price, and it is the only form that still means the same thing tomorrow.
|
||||
|
||||
## A complete run, one garage to storage
|
||||
|
||||
Putting the pieces together, with the parts that matter in production: a browser that
|
||||
looks like a browser, a scope loop, and a write that happens per garage rather than at the
|
||||
end.
|
||||
|
||||
```python
|
||||
import json, re, time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
def read_bands(page):
|
||||
bands = []
|
||||
for row in page.query_selector_all("table.rates tbody tr"):
|
||||
cells = [c.inner_text().strip() for c in row.query_selector_all("td")]
|
||||
if len(cells) < 2:
|
||||
continue
|
||||
m = DURATION.search(cells[0])
|
||||
if not m:
|
||||
continue
|
||||
bands.append({
|
||||
"from_minutes": to_minutes(m.group("lo"), m.group("lo_unit") or m.group("hi_unit")),
|
||||
"to_minutes": to_minutes(m.group("hi"), m.group("hi_unit")),
|
||||
"label": cells[0],
|
||||
"amount": cells[1],
|
||||
})
|
||||
return bands
|
||||
|
||||
def scrape_garage(page, url):
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
page.wait_for_selector("table.rates tbody tr, .rates-unavailable")
|
||||
if page.query_selector(".rates-unavailable"):
|
||||
return {"url": url, "observed_at": time.time(), "tariffs": [], "note": "no published rates"}
|
||||
|
||||
tabs = page.query_selector_all("[role='tab'], .rate-tabs button")
|
||||
tariffs = []
|
||||
if not tabs:
|
||||
tariffs.append({"scope": "default", "bands": read_bands(page)})
|
||||
else:
|
||||
for tab in tabs:
|
||||
scope = tab.inner_text().strip()
|
||||
tab.click()
|
||||
page.wait_for_selector("table.rates tbody tr")
|
||||
tariffs.append({"scope": scope, "bands": read_bands(page)})
|
||||
|
||||
return {
|
||||
"url": url,
|
||||
"observed_at": time.time(),
|
||||
"tariffs": tariffs,
|
||||
"notes": [n.inner_text().strip()
|
||||
for n in page.query_selector_all(".rate-notes li, .rates-footnote")],
|
||||
}
|
||||
|
||||
with InvisiblePlaywright(seed=42) as browser, open("garages.jsonl", "a", encoding="utf-8") as out:
|
||||
page = browser.new_page()
|
||||
for url in garage_urls:
|
||||
record = scrape_garage(page, url)
|
||||
out.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
page.wait_for_timeout(3000)
|
||||
```
|
||||
|
||||
The `flush` on every garage is deliberate. A run over a city is long enough to be
|
||||
interrupted, and a buffered file that dies with the process loses an hour of polite
|
||||
requests you will have to make again. The wider version of that argument is in
|
||||
[resuming an interrupted scrape](how-to-resume-an-interrupted-scrape-playwright.md).
|
||||
|
||||
The `seed=42` is what makes two runs comparable. A fixed seed pins the browser identity,
|
||||
so a difference between Monday's rates and Tuesday's is a difference in the tariff rather
|
||||
than in which visitor the site thought it was serving.
|
||||
|
||||
## Why parking sites block, and what actually helps
|
||||
|
||||
Parking operators sit behind commodity edge protection more often than their size
|
||||
suggests, because their booking flows are a target for card testing. That has two
|
||||
consequences for a rate scraper.
|
||||
|
||||
The first is that a plain HTTP client is usually refused before it sees a tariff table at
|
||||
all, which is why this page drives a real browser rather than requesting the page. A
|
||||
patched Firefox driven by stock Playwright presents a consistent TLS handshake, a
|
||||
plausible fingerprint and a real event stream, so the request that asks for the rates
|
||||
looks like the request a person's browser makes.
|
||||
|
||||
The second is subtler and specific to this data. Protection frequently degrades rather
|
||||
than refuses: you get the page shell, the table renders empty or with placeholder dashes,
|
||||
and nothing signals an error. A scraper that only checks for an HTTP error records a
|
||||
garage with no tariffs.
|
||||
|
||||
Guard on the positive signal rather than the absence of a negative one:
|
||||
|
||||
```python
|
||||
rows = page.query_selector_all("table.rates tbody tr")
|
||||
parsed = [r for r in rows if DURATION.search(r.inner_text())]
|
||||
if rows and not parsed:
|
||||
raise RuntimeError("table present but no band parsed: treat as a failed read")
|
||||
```
|
||||
|
||||
That check is the local version of a rule that runs through this whole corpus: a
|
||||
suppressed or emptied signal is a failure, not a result. The general form, and the order
|
||||
to debug it in, is in
|
||||
[scraping without getting blocked](how-to-scrape-without-getting-blocked.md).
|
||||
|
||||
## A schema that survives the next redesign
|
||||
|
||||
One row per band, with the scope and the garage attached, plus a separate table for notes:
|
||||
|
||||
| column | example | why it is separate |
|
||||
|---|---|---|
|
||||
| `garage_id` | `central-01` | stable across redesigns, unlike the page URL |
|
||||
| `scope` | `Weekend` | the same garage has several tariffs |
|
||||
| `from_minutes` / `to_minutes` | `0` / `120` | the band, in one unit |
|
||||
| `amount_text` | `£4.50` | unparsed, so the currency survives |
|
||||
| `label` | `Up to 2 hours` | the original string, for auditing a bad parse |
|
||||
| `observed_at` | epoch seconds | tariffs change, and you want the history |
|
||||
|
||||
Keeping `label` and `amount_text` unparsed is what lets you re-derive everything later
|
||||
when a site starts writing "2 hrs" instead of "2 hours". Deriving at read time costs
|
||||
nothing; re-scraping a city because you stored only a float costs a week.
|
||||
|
||||
Store it in [a SQLite database](how-to-scrape-into-a-database-playwright.md) if you will
|
||||
query it, or [JSON Lines](how-to-scrape-to-json-lines-playwright.md) if you will
|
||||
reprocess it. Either way, append rather than overwrite: a parking tariff that changed last
|
||||
month is the most interesting row in the table, and an updated-in-place record cannot tell
|
||||
you it ever moved.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why does the price I scraped not match what the garage charges?** Because a tariff
|
||||
table is a set of duration bands and the amount depends on when the car arrives and
|
||||
how long it stays. A single headline number is one band read out of context, and the
|
||||
small print underneath the table, the daily maximum and the minimum charge, usually
|
||||
outranks the table itself.
|
||||
|
||||
**How do I know which tariff table I am looking at?** Read the scope, not just the
|
||||
rows. The same garage publishes weekday, weekend, event-day and overnight tables, and
|
||||
the page often names the scope once, above the table, then never again. Store the
|
||||
scope on every band you capture.
|
||||
|
||||
**The rates only appear after I fill in a date. Is that a block?** No, it is the
|
||||
normal flow on most operator sites: the table is computed from the arrival and
|
||||
departure you enter. Drive the date control the way a person would and wait for the
|
||||
table to repopulate before reading it.
|
||||
|
||||
**How fast can I crawl parking sites?** Slowly. These are small sites and a city-wide
|
||||
sweep at full speed is a visible load on infrastructure that was sized for a few
|
||||
hundred human visitors a day.
|
||||
|
||||
**See also:** [How to scrape accordion and tab content with
|
||||
Playwright](how-to-scrape-accordion-and-tab-content-playwright.md), [How to rate limit
|
||||
your own Playwright scraper](how-to-rate-limit-your-scraper-playwright.md), [How to
|
||||
resume an interrupted scrape with
|
||||
Playwright](how-to-resume-an-interrupted-scrape-playwright.md)
|
||||
|
||||
## Sources
|
||||
|
||||
- Playwright, Locators, https://playwright.dev/python/docs/api/class-locator -
|
||||
`evaluate_all` and the locator waiting model, checked for reading a whole table in
|
||||
one pass instead of one call per row.
|
||||
- This project's pages on pacing and on resuming an interrupted run, which carry the
|
||||
behaviour this page depends on instead of repeating it.
|
||||
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user