Compare commits

...
53 Commits
Author SHA1 Message Date
Federico 8c24507b5a A gate on the guides, and the one live defect it found (#178)
* A gate on the guides, and the one live defect it found

Nothing was reading the 454 pages in docs/. One of them published
`tree = page.accessibility.snapshot()`, an attribute this fork does not have
and does not refuse by name, so anybody who ran that block got an
AttributeError. It is corrected to page.aria_snapshot(), which exists.

scripts/check_docs_api_surface.py asks the REAL classes what they have and
refuses any name in a ```python block that is not there. Two other designs
were measured first and rejected, and the reasons are in the docstring so
nobody rebuilds them: parsing every block fails on 82 of 1169 deliberate
fragments, so it would be born red on correct pages; and checking attributes
on a returned value would not have caught the defect that prompted all this,
because in that one the attribute was real and the runtime value was None.

Five known-bad inputs and seven that must not fire, because a gate that
refuses everything is as useless as one that passes everything. The foreign
objects that share a name - an httpx response, a pdfplumber page, pytest's
request fixture, an hrequests page - are skipped by the library the block
names, and every entry there came from a measured false positive.

Required by the gate job, and skipped rather than faked green during the
window where the pinned core is not yet on the index, exactly as unit is.

* The prose said the old name too, and the gate cannot see prose

Fixing the code block left the sentence under it still promising
accessibility.snapshot(). The gate reads only ```python blocks - that blind
spot is declared in its docstring, and it took about a minute to bite.

A page whose prose contradicts its own example is worse than either half
being wrong alone, because a reader believes the sentence.
2026-09-08 03:20:02 +02:00
github-actions[bot]andfeder-cr 39010ed45e record 0.13.2 as published, and date it the day the index took it (#176)
* record 0.13.2 as published

* Run the checks the bot's token cannot trigger

* Date 0.13.2 the day the index took it

The upload is 2026-09-07T23:53Z; the heading said 2026-09-08, which is the
local date an hour later. test_the_changelog_documents_every_version_it_claims_to_cover
compares the two and is right to refuse.

---------

Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-09-08 02:14:55 +02:00
Federico d34a11e886 Thin out one repeated construction, and give the last eight orphans a home (#177)
Two related pieces of corpus hygiene.

The first: "rather than" ran at 2.60 per thousand words across 454 pages, with
one page using it sixteen times. A construction repeated at that rate is a
signature and not a style, which this corpus established in July when the same
phrase was cut from 63 uses across 21 pages down to 23. The corpus has grown
twentyfold since and nobody recounted.

136 pages were over five uses. 351 of them are rewritten, bringing every page
to five or fewer and the corpus mean from 4.4 to 3.6 per page.

The rewrites are varied on purpose. Replacing all 351 with "instead of" would
have taken that phrase from 1.19 to 1.65 per thousand words, which is trading
one signature for another. The load is spread by syntactic context instead: a
gerund takes "instead of", a preposition and a bare noun take a comma and
"not", a determiner alternates between the three. The result moves "rather
than" from 2.60 to 2.14, "instead of" from 1.19 to 1.32, ", not" from 2.45 to
2.71, and "in place of" from 0.01 to 0.05. Nothing spikes.

Verbs in the base form were left alone: rewriting those needs a judgement per
sentence, they are only 30 cases in the corpus, and there were plenty of safe
candidates without them.

The second piece: eight pages published on 5 September had no inbound link
from anywhere in the prose. Each now has one entry in the body of the pillar
it declares as its parent, in the section it belongs to. Both corpora are now
at zero orphans. Worth stating plainly, because the obvious reading is wrong:
this is not an indexing fix. All eight are outside Google's index, and so are
the two pages of the same wave that did have inbound links.

Internal links all resolve, no line endings touched, and the four files with
unbalanced brackets are code samples that were already that way.
2026-09-08 02:01:55 +02:00
Federico 5f528357a6 Return the navigation Response from goto, reload and history (#174)
goto answered None on every navigation because op_goto ended with a hardcoded {"response": None}. The page loaded, the response events carried the right statuses and expect_response worked; only the return value was missing, so page.goto(url).status was unreachable. Crawlee reads that value and treats None as a failed load, so a PlaywrightCrawler driven by this package failed every request: 0 finished / 2 failed before, 2 / 0 after, against a local server.

The engine needed no change. navigationId is set only on the main document channel and is inherited by every hop of a redirect chain, so PageDispatcher can index the document request by it exactly. reload and the history commands share the fix.

Released as 0.13.2, because the version job correctly refused a head whose wheel files had moved while pyproject still declared a version the index already serves.
2026-09-08 01:50:07 +02:00
Federico 70a8164d26 Give the twenty September guides the blocks the house format requires (#175)
The wave published on 7 September went out without the question block, the
See also line and the Sources section: rules 6, 7 and 8 of the format every
article on this wiki follows, missing on all twenty. 416 of the other engine
pages carry the question block, which is the long-tail capture device, so the
gap was in these twenty and not in the convention.

Each page gets four questions in the words people actually type, answered from
what the page already argues, so no new claims are introduced. Each See also
names pages the article already links in its body, using their real titles.
Each Sources section names what the page was checked against: the Playwright
reference for the calls the code makes, and a primary source where one is
genuinely on point - RFC 5545 for the calendar feeds, MDN's getComputedStyle
and content for the pseudo-element page, MDN's aria-label for the page about
numbers drawn as images, PyPI's stats API for the download-count page. Every
one of those nine URLs was fetched and returns 200.

Purely additive: 668 lines added, none removed, no line endings touched.
2026-09-08 01:44:02 +02:00
Federico 8a8dc8d0fd Give the twenty new guides their inbound links (#173)
They shipped with zero inbound internal links, against the register's own rule
that a new page goes into the body of the relevant pillar. The pillar here is the
Scraping with Playwright hub, and adding them to it is that page's purpose rather
than stuffing: nine into the vertical section beside the flight, crypto and
directory guides, eleven into the objects section in its filename order.

The in-body links are only two, and the reason is the rule that the anchor must
already exist in the sentence. Six candidates matched a search; four were false
positives on inspection. The printer-friendly guide already writes
getComputedStyle(el, "::after").content while explaining that generated content
is not in the DOM, and the transport timetable guide already says a live
departure board is not a timetable. Those two are links. The other four were
opac inside opacity: 0, sprite sheets in a list of sub-resources, and
Playwright's platform compatibility table, and writing a sentence around any of
them would have been the stuffing the rule exists to prevent.

The hub edit is twenty added lines and no removed ones, verified against a copy
taken before the change, after restoring CRLF: the script that inserted them had
rewritten the whole file to LF, which would have shown as a 199-line rewrite.
2026-09-07 23:59:12 +02:00
Federico 648aacfabd Put our own measurements into the two guides that can carry them (#172)
The twenty guides shipped without a single measurement of our own, which is the
one thing the article method treats as more important than length. Two of them
can host one truthfully, and these are those two.

CSS pseudo-element content now carries the closed shadow root finding. Two
Playwright issues describe what look like separate problems, #23047 (locators
cannot enter mode:"closed" roots, open since May 2023, 26 comments) and #30816
(Page.content() does not serialize shadow DOM at all, closed, 2 comments). They
are one gap seen from two sides, and nobody has connected them: the search
`repo:microsoft/playwright 30816 23047` returns exactly two results, the two
issues themselves, re-verified against the API today rather than taken from the
research note. That is why advice for one symptom never helps with the other.

Numbers rendered as images now carries the canvas bench result. Hashing the PNG
bytes of the same page across three runs gave three different md5 values on
unmodified retail Firefox, which reads as canvas randomisation and is false: the
files had identical byte length and differed only in encoder metadata. Comparing
the decoded pixel array instead, all three runs were stable. The rule that falls
out is concrete for anyone watching a rendered number for change, and it comes
with the code.

The other eighteen are left alone rather than given a decorative statistic. A
measurement belongs to an article only when the article is actually about the
thing measured.
2026-09-07 22:50:47 +02:00
Federico c61579c2f4 Extend the twenty new guides to the length the corpus publishes at (#171)
They shipped at 851 words on average against roughly 1,900 for the pages that
rank, which was stated at the time as open work. Each one now carries three more
sections, and the additions are substance rather than padding:

- a complete run, end to end, with the parts production needs: a resumable loop,
  a flush per record so an interrupted run leaves usable data, and the guard that
  distinguishes an empty result from a failed read;
- what the specific target does when it decides to stop serving you, which
  differs sharply by domain. Carrier endpoints defend against enumeration,
  comparison engines are slow rather than hostile, bank sites cache hard, court
  portals rate limit and do not forgive, school sites simply go stale, and
  library catalogues degrade by session rather than by policy;
- the schema, with the question each grain exists to answer: connector-level
  transitions for charger utilisation, event logs for adoption waiting times,
  status history for permit durations, both timestamps everywhere so staleness is
  measurable rather than assumed.

Several also gained the check that separates a real absence from a silent
refusal, which is the failure this corpus keeps meeting: a table that renders
empty, a town with no stations, a docket that lost its entries, a series that
returns zeros. Each is now a distinct outcome rather than a plausible row.

Average is now 1,433 words, from 851. That is closer to the corpus norm and still
short of it, and saying so is more useful than padding to a number: the measured
data says length does not separate the pages that rank from the ones that do not.
2026-09-07 21:52:03 +02:00
Federico 0bd093d285 Twenty new scraping guides, chosen from the ranking data (#170)
Which topics win is now measured rather than assumed. Among the pages Google has
indexed, our own-title queries rank 84% of the time and generic demand queries 4%,
and the ten indexed pages that lose on their own title are the most generic
Playwright and scraping subjects: generating a PDF, rate limiting, e-commerce
product pages, headless versus headed, recording a trace. That family was
excluded on purpose.

The twenty added here are narrow objects or mechanisms, each with a different
technical problem at its centre so they do not read as twenty variants of one
article:

  duration bands rather than a price          parking rates
  live status with two distinct timestamps    EV charging availability
  the location decides the result             fuel prices
  seasonality, and cancellations as events    ferry schedules
  session-bound catalogue, copies per branch  library availability
  a timeline that reorders and gets revised   package tracking
  a DOM rewritten while you read it           flight status boards
  a unit that changes underneath you          snow reports
  the disappearance is the data               pet adoption listings
  postback forms, and a resumable run         construction permits
  never enumerate, only known cases           court dockets
  deadlines that are frequently not dates     scholarship listings
  a grid of parallel tracks, and timezones    conference agendas
  the series behind the chart                 package download statistics
  the footnote that changes the number        bank interest rates
  a quote is a function of its inputs         energy tariffs
  prefer the calendar feed, expand inclusive  school term calendars
  cascading dropdowns, a cross product        spare part compatibility
  sprites and remapped fonts, and when to stop numbers rendered as images
  not in the DOM at all                       CSS pseudo-element content

They sit at nav_order 150 to 169 under Scraping with Playwright, with no
collisions and no internal links broken. Every page carries the honest limits of
its subject, including the cases where the right answer is to stop and ask the
site for the data instead.

One deviation from the house standard, stated rather than hidden: these average
851 words against roughly 1,900 for the corpus that ranks. Length was measured
and does not separate winners from losers on its own, but extending them is
still open work.
2026-09-07 21:18:57 +02:00
Federico 61fde53457 The server's command is uvx aihawk (#169)
Since aihawk 0.11.0 the MCP server is aihawk with no subcommand, so the one line a reader copies is claude mcp add stealth -- uvx aihawk, and the pages that name the server call it aihawk. The old command keeps working through the shim but is not what a new reader should copy.
2026-09-07 00:55:24 +02:00
Federico 823217b484 The MCP server lives in AIHawk: the two repository links and the family bullets say so (#168)
The server repository was merged into AIHawk (aihawk 0.10.0, module aihawk.mcp); the PyPI name invisible-playwright-mcp stays as a shim, so the commands on these pages are unchanged and only the links move: to the wiki page that now holds the server's config blocks, settings and tools.
2026-09-07 00:54:55 +02:00
Federico b8243bb0c2 The MCP server lives in AIHawk: the two repository links and the family bullets say so (#167)
The server repository was merged into AIHawk (aihawk 0.10.0, module aihawk.mcp); the PyPI name invisible-playwright-mcp stays as a shim, so the commands on these pages are unchanged and only the links move: to the wiki page that now holds the server's config blocks, settings and tools.
2026-09-07 00:13:39 +02:00
Federico 0f14cc782d The two sibling one-liners run through uvx again (#165)
Owner decision, 2026-09-06, after a survey of comparable projects: pip refuses
outside a virtual environment on current Debian and Ubuntu, and on Windows a
Store Python leaves pip scripts off the PATH, so the one route that works for
every reader is uv. Reverts the pip form of this block from earlier today; the
sibling pages say the same.
2026-09-06 17:03:09 +02:00
Federico d4faa9ebaf The two sibling one-liners install with pip (#164)
The README block that points at the MCP server and at AIHawk showed both
through uvx. Both now read pip install followed by the command, which is how
their own pages say it since 2026-09-06. One wiki page loses the prefix too.
2026-09-06 11:12:32 +02:00
github-actions[bot]andfeder-cr 39e4dd2e0f record 0.13.1 as published (#163)
* record 0.13.1 as published

* Run the checks the bot's token cannot trigger

---------

Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-09-06 04:55:34 +02:00
Federico 76a7a0ce21 Pin invisible-core 29.19.0: the engine is firefox-29, which has the screencast (#162)
* Pin invisible-core 29.19.0: the engine is firefox-29, which has the screencast

page.screencast.start() shipped in 0.13.0 against a sealed engine that could
not answer it; the seal now points at firefox-29, which carries the screencast
and crops the Windows resize border out of a full-window frame. The pin
follows the seal and nothing else moves. Version 0.13.1.

* 0.13.1 is dated by the clock in UTC, not the one on the desk
2026-09-06 04:39:38 +02:00
github-actions[bot]andfeder-cr 0d65c54eb6 record 0.13.0 as published (#160)
* record 0.13.0 as published

* Run the checks the bot's token cannot trigger

---------

Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-09-06 03:00:21 +02:00
Federico 5a786f43d6 The 0.13.0 changelog heading is dated by the upload (#161)
PyPI records the 0.13.0 upload on 2026-09-05 UTC; the heading said the 6th,
which was the local date after midnight. test_release_e2e compares the two
and it is right to.
2026-09-06 02:45:22 +02:00
Federico 1f6f8d1ac8 page.screencast streams JPEG frames of the window, pointer included (#159)
* page.screencast streams JPEG frames of the WINDOW, pointer included

page.screenshot() is the content viewport and can never show the pointer:
it is drawn in the chrome document so that no page can see it. The engine's
screencast is back since firefox-28, rebuilt on the browser's own window
capture with a fullWindow flag of ours, and the in-process Juggler server
now answers screencastStart and screencastStop with it. Every frame the
engine sends goes up to the vendored client under the names it reads and
is acknowledged from the reader thread with a new Connection.post, which
sends without waiting: a send there would wait for a reply only that
thread can deliver. The pipe gets a write lock, because two threads now
write it. A video file (path=) is refused by name: there is no encoder.

Measured against the objdir build: under headless=True, which on Windows
is the cloaked window, 146 frames in fifteen seconds at the requested ten
per second, 782x676 with 87 percent of the pixels being the page served
and none black - the capture reads a cloaked window. The unit tests build
a PageDispatcher without a browser and were run against three known-bad
inputs, listed in the module docstring.

* Version 0.13.0: the screencast is a feature, not a fix

The changelog entry moves from Unreleased to 0.13.0, dated today.

* The screencast e2e skips, by name, on an engine that has no screencast

The CI drives the sealed engine, firefox-27, which has no
Page.startScreencast: the first run went red on that sentence with 206
other tests green. Until the seal rolls to firefox-28 the test skips
naming the engine; any other refusal is still a failure.
2026-09-06 01:51:33 +02:00
github-actions[bot]andfeder-cr 95c791d351 record 0.12.3 as published (#158)
* record 0.12.3 as published

* Let the gate run on the ledger branch

* The 0.12.3 entry carries the index's date

The upload landed on 2026-09-05 UTC; the entry said 2026-09-06, the local
calendar at the time of the tag. test_the_changelog_documents_every_version_it_claims_to_cover
compares the two and was right to refuse.

---------

Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-09-06 01:10:02 +02:00
Federico 907150bf60 Pin invisible-core 27.19.0: orphaned .tmp trees in the engine cache are swept (#157)
A download killed during verifying or extracting used to leave up to the whole
extracted tree under cache_root()/.tmp-<tag>-<pid>, because only a fresh
download by the same pid ever removed it. The core now sweeps the trees whose
process is gone on every ensure_binary, warm path included, and leaves alone
its 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 turned a killed
download from a Ctrl-C into an ordinary event.

Pin moved with scripts/sync_core_pin.py after the core landed on the index.
Version 0.12.3, a pin bump: nothing this package launches the browser with
changed.
2026-09-06 00:37:38 +02:00
Federico d86f52c9c8 The README says the one thing the stock driver cannot do (#155)
Playwright's own docs rule out closed-mode shadow roots, and measured this
week stock Playwright returns nothing for that content in Firefox and
Chromium alike while this engine returns the element, with the page still
reading null from shadowRoot. That was documented on the wiki and nowhere a
reader would see it. One paragraph, the measurement, and the link to the
page that prints the reproduction.
2026-09-05 15:36:17 +02:00
Federico 686607738e Ten mechanics pages, and one correction the measurement forced (#154)
Three arms on one local page settled a claim this wiki had been making
confidently: stock Playwright finds nothing inside a closed shadow root,
in Firefox and Chromium alike, while this engine reaches the content with
the page still reading null from shadowRoot. The shadow DOM page said the
boundary was absolute for everyone; it now says what was measured, and
links the new page that prints the reproduction.

Two more recipes died the same way, which is why every code block in this
wave was executed before it shipped. The keyboard fallback everyone
recommends for a stubborn dropdown, click then ArrowDown then Enter, does
not move the value at all: focus without the click does. And
document.fonts.check() answers true for a font family invented on the
spot, so it cannot tell you whether a container has the font you think.

The rest: Queue-it waiting rooms and why there is nothing there to defeat,
memory on long runs with the measurement method that does not double count
a previous browser, ARM64 Linux, fonts in slim images, canvas across
operating systems, downloading linked PDFs (where the out-of-page request
API is refused by design and the in-page fetch is the route), select
options for native and custom dropdowns, a browser-use comparison with the
conflict declared, and the Windows first-launch failure with the registry
correlation reported as our observation rather than an architecture claim.
2026-09-05 13:22:23 +02:00
github-actions[bot] e2b795eea4 record 0.12.2 as published (#152)
The ledger entry the publish workflow wrote for 0.12.2, from the artifacts the index serves.
2026-09-05 12:36:32 +02:00
Federico 4ddf1f9fb7 The persistent-profiles page names the defect that was ours (#153)
The page listed two upstream Playwright reports about cookies vanishing between
runs and told the reader to look there before rewriting their own code. From
0.8.0 to 0.12.0 this client dropped them itself: the persistent launch handed
back a Juggler container whose storage dies with the session. Fixed in 0.12.1;
a reader on one of those versions should upgrade before reading anything else,
and the page now says so.
2026-09-05 12:36:12 +02:00
Federico 790a123c86 0.12.2: the launch counter lives on the engine's repository (#151)
The pin moves to invisible-core 27.18.0, which declares the launch counter's
address in every session: the usage-counter release of the repository that
builds and ships the engine. The engine's compiled default says the same from
the next build. Engines older than firefox-21 do not read the pref and are not
counted; the ping can be turned off with invisible_firefox.usage_ping.enabled.
2026-09-05 12:24:24 +02:00
Federico 0d2dae5862 The browser launches badge is back, because the number behind it is live again (#150)
It went in 0.7.2, when the counter it read lived on a repository that had just
been deleted: the renderer would have redrawn the last real value every morning,
and a frozen figure presented as current is worse than none. The counter has
lived on this repository since 2026-08-19 and has been counting since, about
twenty thousand launches a day at the moment, so the badge shows a live number.

It is cumulative and it undercounts: engines before firefox-21 carry the old
address compiled in and rejoin the count only as their users upgrade.
2026-09-05 04:23:52 +02:00
github-actions[bot] 101b8099fe record 0.12.1 as published (#149)
The ledger entry the publish workflow wrote for 0.12.1, from the artifacts the index serves.
2026-09-05 04:09:12 +02:00
Federico 874277167f A persistent profile keeps its cookies and storage for the next session (#148)
Since 0.8.0 profile_dir kept nothing. The persistent launch handed back an
ordinary context: Browser.createBrowserContext, a Juggler container with its
own userContextId, whose destroy() calls ContextualIdentityService.remove and
deletes the container's cookies and storage with the identity. The first
session set a cookie and a localStorage entry and read both back; the second
session on the same profile read an empty jar and None; cookies.sqlite in the
profile held zero rows throughout. Measured 2026-09-05 against the published
0.12.0 from a clean environment.

Upstream's persistent context is the browser's default one, userContextId 0,
whose state is the profile's. It is addressed by omitting browserContextId,
never by null, because Juggler registers it under undefined and Map.get(null)
finds nothing; and it is never removed, closing it closes the browser. One
function now owns that rule and every command that names a context goes
through it, so the twelve option pushes, newPage, the cookie commands and
close all agree.

The e2e writes a cookie and a localStorage entry in one session, reads the
cookie row from cookies.sqlite on disk in between, and reads both back in a
second session on the same profile. Against 0.12.0 it fails on the on-disk
read. Three pure tests pin the addressing rule, including the null trap.
Version 0.12.1.
2026-09-05 03:48:55 +02:00
github-actions[bot] 0828d6b9b0 record 0.12.0 as published (#147)
The ledger entry the publish workflow wrote for 0.12.0, from the artifacts the index serves.
2026-09-04 20:58:08 +02:00
Federico 0a16b783d6 0.12.0: the engine moves to firefox-27, where the first launch on Windows works (#146)
The pin goes to invisible-core 27.17.0, which seals firefox-27. That engine
changes one thing: on Windows the launcher process forwards the Juggler pipe it
is handed in the environment instead of reading CRT descriptors this client
never opens, so the first launch from a path the browser had never run from no
longer exits with 3221226505. Everything else in the engine is firefox-26.

The changelog entry says what it was, why it failed exactly once per machine,
and since when; the test that keeps it fixed is the commit before this one.
2026-09-04 20:46:17 +02:00
github-actions[bot] 31ba882e6d record 0.11.0 as published (#143)
The ledger entry the publish workflow wrote for 0.11.0, from the artifacts the index serves.
2026-09-04 18:23:43 +02:00
Federico fc7915483f The version gate asks whether the package moved, not whether the number is taken (#145)
On its first day the gate refused the two pull requests that follow every
release: the ledger the publish workflow opens by itself, and the changelog
entry for the release. Both carry the published version, and a bump on either
would be a lie, because nothing that ships had moved.

The question it asks now is the one it always meant. Since the tag of the
published version, has anything changed that goes into the wheel, the package
tree the build backend names or pyproject.toml? The ledger, the changelog,
tests, workflows and docs alter nothing anybody installs and pass without a
bump; a change under the package does not. The tag has to be in the checkout,
so the version job fetches the full history, and a taken version with no tag
in the clone is refused rather than guessed at.

Two known-bad inputs: a pure classifier fed the ledger, the changelog, a test,
a workflow and a same-prefix sibling of the package, which must all not count,
against files under the package, which must; and the previous release's tag,
from which the package moved by definition.
2026-09-04 18:17:42 +02:00
Federico fc0a2827ac Fifteen commits of content under a version the index already served (#142)
Measured 2026-09-04: 0.10.0 is on the index while main sat on 0.10.0 with FIFTEEN
commits on top of the tag - 39 files, 841 insertions, the screenshot clip fix
among them. A release from there would have published NOTHING and reported
success, because publish.yml asks the index first and treats an already-present
version as a deliberate no-op. That is right for a re-pushed or backfilled tag
and indistinguishable from somebody forgetting to bump, so the fix could not have
reached anybody and nothing would have said so.

This is the third package with the same hole; the sibling found it first. The
check asks the index whether the version a change proposes is still free, on pull
requests only - on main straight after a release the version IS the published one
until somebody bumps, and a gate that is red at rest is one people learn to skip.
Bumping publishes nothing, so the rule costs one line in the change that earns
the release. Hence 0.11.0.

⛔ The known-bad input is PER PACKAGE, and copying it from a sibling was wrong.
It said 0.1.0, which this package has never published - the oldest here is 0.3.5.
The test failed rather than passing on a version that does not exist, which is
the only reason the mistake was visible.

Three outcomes rather than two: a network error is neither present nor absent,
and scoring it as absent turns an unreachable index into a green gate.
2026-09-04 13:15:28 +02:00
SamadhiFire f2474beb0b Two launch gates stop calling the removed path command (#141) 2026-09-04 13:10:33 +02:00
Federico 03f695d813 Merge pull request #140 from feder-cr/docs/differentiation-wave
Three twin pages stop sharing a title's intent, and the pairs the tracker cleared stay put
2026-09-04 02:03:56 +02:00
feder-cr 3b6fee9957 Three twin pages stop sharing a title's intent, and the pairs the tracker cleared stay put 2026-09-04 01:57:16 +02:00
Federico f4f5f13629 Merge pull request #139 from feder-cr/docs/audit-code-fixes
Twelve pages stop shipping code that cannot run as pasted, and two claims catch up with their sources
2026-09-04 00:43:40 +02:00
feder-cr 3fbbf6dd30 Twelve pages stop shipping code that cannot run as pasted, and two claims catch up with their sources 2026-09-04 00:36:26 +02:00
Federico c08444186e Merge pull request #138 from feder-cr/docs/strip-image-metadata
Tool metadata out of the shipped screenshots, and a code sample readers can actually read
2026-09-04 00:28:46 +02:00
feder-cr 52a1fc0859 Tool metadata out of the shipped screenshots, and a code sample readers can actually read 2026-09-03 22:12:05 +02:00
Federico 0f48c05214 Merge pull request #137 from feder-cr/docs/agent-layer-links
The engine's front page now names the agent that sits on it
2026-09-03 20:24:18 +02:00
feder-cr 4438689e40 The engine's front page now names the agent that sits on it 2026-09-03 20:17:43 +02:00
Federico bf72778dcc A screenshot photographs where the page is, and full_page means the page (#136)
* A screenshot photographs where the page is, and full_page means the page

Found by looking, not by reading. Asked to open a README in a browser and
actually look at it, I scrolled to the part I wanted and took a picture, and the
picture was the top of the page. scrollY 3000, the target element at y=0 in the
viewport, and the image showing the document's first screen.

One line. op_screenshot built its clip as {x: 0, y: 0, width: innerWidth,
height: innerHeight}. The engine reads a clip in DOCUMENT coordinates, so that
is not the viewport: it is the document's top-left corner, at viewport size. Two
promises broke on it, both silently, both returning a valid image of the wrong
place.

Scrolling did nothing. An agent that scrolls and looks got the same picture
every time, with nothing in the image to say so. That is what
browser_take_screenshot does in the MCP server, and rung 3 of the ladder that
server hands every model is "take a screenshot, then click on what you can see" -
so the server was recommending a step that could not work.

And fullPage was never read by the driver at all: 800x600 on a document asked
for at 800x4000.

Fixed where it comes from rather than where it shows: the clip is computed from
the page, either where the viewport actually is or how big the document actually
is. A clip the CALLER supplies passes through untouched, because Playwright
documents it in page coordinates already.

Six tests, and they read PIXELS. A size proves the crop has the right shape, and
the defect was a right-shaped crop of the wrong place, so the fixture page has a
red band at y=1000 and a green column at x=1400 and the assertions ask what
colour came back. The PNG reader is thirty lines of zlib rather than adding
Pillow to the dev extras so one test can read one pixel.

Six mutations, six killed. The first round had one survivor, the horizontal
axis, because nothing scrolled sideways - I had labelled it as expected to
survive, which is a polite way of saying half a two-axis fix was untested. It is
covered now.

Two of my assertions were also wrong rather than the code: adding the green
column made the document 1600 wide, so full_page correctly answered 1600x4000
while the test demanded 800x4000, and scrollTo(1400, 0) is clamped to 800 in an
800px viewport, so I was reading the wrong pixel. The test now reads scrollX
back and computes from it instead of assuming, which is the same mistake in
miniature as the defect it covers.

The vendored upstream suite could not have caught this. It is excluded from
collection, but that is the smaller half: its test_screenshot.py has three tests,
and neither fullPage nor scrolling is among them.

* Translate the identifiers I just wrote in Italian, and say why nothing stopped me

The English gate went red on CI for the test file added in the previous commit:
`landed`, `out` and `prior` were `dove`, `fuori` and `sopra`. I wrote Italian
into a public repository on the same day I wired that gate into this repo's CI
for exactly this.

⛔ And the reason it passed locally is worth more than the mistake. The gate
walks `git ls-files`, so it sees TRACKED files only. Running it before `git add`
on a brand-new file scans everything except the file being added, and reports
clean. It is not wrong to read the tracked set - that is what ships - but it
means the local run before a first commit cannot see the thing most likely to be
wrong, and only the CI run after the push does.

Nothing to change in the gate. What changes is when it is run: after staging,
not before.
2026-09-03 17:25:13 +02:00
Federico 83403b83a7 Merge pull request #135 from feder-cr/docs/discovery-links
The README learns the vendor pages exist, and the agents hub points across
2026-09-03 15:39:09 +02:00
feder-cr 12fd16385a The README learns the vendor pages exist, and the agents hub points across
Eighteen anti-bot vendor pages went live in the wiki without a single link
from the repository's own README, which is the page crawlers actually visit.
Now the documentation section names the set. The AI-agents hub also gains a
pointer to the AIHawk wiki, where the agent-experience content moved: the
split is developers wiring an agent to this engine here, people running an
agent there.
2026-09-03 15:32:36 +02:00
github-actions[bot]andfeder-cr 2b4f83f7f2 record 0.10.0 as published (#132)
* record 0.10.0 as published

* Trigger the required checks

The branch below was pushed by a workflow using GITHUB_TOKEN, and GitHub does
not let that token start other workflows. So tests.yml never ran, the required
`gate` context never arrived, and the pull request was not slow: it was
unmergeable. An empty commit pushed with a real token is what starts them.

Documented in 17-release-seal-spec.md step 8, and this is the second release it
has happened to.

---------

Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-09-03 15:02:07 +02:00
Federico 38ac9d5259 Merge pull request #134 from feder-cr/docs/agent-pages-moved-to-aihawk
Four agent pages moved to the AIHawk wiki, and their slots point across
2026-09-03 14:43:48 +02:00
Federico 9cd79b98bc Put Added first in the 0.10.0 entry, where the reader looks (#133)
Closing the changelog for the release left the three subsections in the order
they were written rather than the order this file's own header says it follows:
Documentation, Internal, then Added. The release page is generated from that
section, so the headline of the release - nine acting methods on ElementHandle -
came third, under two sections about prose and CI.

Reordered, and the release notes regenerated from it.
2026-09-03 14:41:22 +02:00
feder-cr 011b1c35d3 Four agent pages moved to the AIHawk wiki, and their slots point across
The agent-experience versions of the timing signal, the retry-loop volume
signal, computer-use detection and browser-use's config surface now live on
the AIHawk wiki, told in agent language for the audience that runs an agent
rather than builds one. The originals become pointers so the eight pages
that link them keep working, each keeping a one-paragraph summary and its
local mechanism links. The mechanism layer itself does not move.
2026-09-03 14:38:19 +02:00
Federico 2b85b111eb 0.10.0: an ElementHandle can act, and the docs stop contradicting the product (#131)
* Land four docs edits that were rescued once and then lost again

On 2026-08-30 four wiki pages were found edited in the working tree and never
committed. They were rescued onto a branch, and the branch was never merged, so
the same work has now been lost twice: once to an uncommitted tree, once to a
branch nobody opened.

Three of the four were untouched on main since 28 and 29 August, so main is
byte-identical to the rescue's parent and taking the rescued version applies
exactly the rescue. The fourth is the page I edited today, so its addition went
in by hand: a FAQ entry saying an agent is not made undetectable by one setting,
because the engine fingerprint, the machine's own surfaces and the agent loop's
rhythm are three separate problems. Both edits now stand.

The course-catalog guide's change is the one worth checking rather than trusting:
it rewrites a code example from query_selector_all plus handle methods to
page.locator, nth, get_attribute and click. The API existing on the client proves
nothing, so it was run against a real page: count, nth, get_attribute, click and
get_by_role all work, and the clicks arrive with isTrusted true. The guide teaches
something that works.

* 0.10.0: an ElementHandle can act, and the docs stop contradicting the product

`page.query_selector("#go").click()` is ordinary Playwright, and this driver
answered "ElementHandle has no method 'click'" - fifty-five methods offered by
the client, fourteen served, every one of them a read. Nine acting methods are
wired, through the same humanised path as the selector versions, because two
click paths would be two fingerprints.

That was already on main. What this release adds is the decision to ship it:
until it is on the index the method fails for everybody, and it is verified in
three places rather than one. The e2e ran it against a real browser in CI, and
both consumers were run against THIS engine rather than the published one -
invisible-playwright-mcp declares an open bound, so a release here changes what
every `uvx invisible-playwright-mcp` install resolves. 147 tests on the server
and 132 on the interface, against this tree.

The documentation half is the larger change by volume. Two pages told readers
there is no MCP server for this project, written before there was one. The
README never named either sibling, so anyone who would rather prompt than script
was handed off to the page that said no server existed. Four wiki pages edited
in a working tree on 2026-08-30 were rescued onto a branch and then lost a
second time when nobody merged it.

And the English-only gate, written for this repository and wired nowhere, now
runs in CI. It found four Italian test files on its first run here.
2026-09-03 14:21:24 +02:00
Federico 386da78813 Run the English gate here, and stop saying there is no MCP server (#130)
* Run the English gate in the repository it was written for

The rule is the owner's, from 2026-08-27, after 549 lines of Italian shipped
here in one subsystem and 852 more were found in 33 files that were already
public. The gate was written that day, in this repository, and wired into
nothing: not tests.yml, not the pre-push hook, whose steps are pytest, pin,
names, internals and publish. Both sibling packages copied the script AND the
CI step. This one kept only the script.

Ran it here for the first time today: four test files, red. Two of them were
last touched on 2026-08-31 by a commit about something else, so nothing was
going to notice.

The four are translated. The diffs are 17 lines across four files, and the
translation was checked by reconstructing each file from its HEAD blob with
only the prose substitutions applied, so every count, date and version in them
is untouched by construction rather than by inspection. One file changed a loop
variable from `nome` to `name`, which is a code identifier rather than prose,
and the rule names variables explicitly.

The job is its own, and deliberately not behind core-on-index: reading files
needs no install, and hanging a language check off the availability of a
package on an index would skip it during exactly the window when releases are
made. The selftest runs first, because a language gate that has only ever
printed clean is the same non-gate as any other.

One thing this does not fix. The gate reads prose, so it sees two Italian
function words in a file and not a lone identifier: `e2e-hunt.yml` has an input
named `giri` and passes. That limit is documented where the gate is described.

* An ElementHandle can act, not only be read

`page.query_selector("#go").click()` is ordinary Playwright, and this driver
answered "ElementHandle has no method 'click'". The client offers fifty-five
methods on a handle and the driver served fourteen, every one of them a read:
the whole acting half was missing, and the error said so honestly while being
useless to anyone migrating.

Nine are wired: click, hover, fill, type, press, focus, check, uncheck,
selectOption. Nine and not fifty-five is a decision - these are the ones a
person hits in the first hour - and the rest keep reporting themselves as
missing rather than being filled in for symmetry.

⛔ They go through the same `actions` as the selector versions, and that is the
whole design. A handle click is the humanised pointer: approach, hover, press,
release, with the hit-target check and the actionability retry. A second,
simpler path would be quicker to write and would give this package two click
behaviours with two fingerprints, which is the one thing it exists not to have.

What differs is exactly what should: the node is not looked up again, because a
handle names one node and re-querying finds a different element with the same
description; and it is not disposed afterwards, because the caller still holds
it.

The tests are in two layers because the defect found while writing them lives
in only one. The lower layer has no browser and checks that the retry loop
treats a caller's element differently from one it resolved itself. The upper
layer drives a real page through the public API, and that is the layer that
caught it: `click` and `fill` accepted the new parameter and quietly failed to
forward it, because their call is formatted differently from the others and a
pattern-based edit missed them. Every lower-layer assertion still passed. The
e2e asserts the hover arrives before the click and that the click is trusted,
because those are what a shortcut would lose.

* Stop telling readers there is no MCP server for this

Two pages said so, and both were written on 2026-07-27, before the server was
published on 2026-08-19. True when written; afterwards they steered readers
away from the thing that solves the problem they then documented a workaround
for.

The integration page opened with "You do not need a separate MCP server" and
its FAQ answered "Is there an MCP server for this project?" with "No, and there
does not need to be". It now opens with ours, and is what it actually is: how
to point Microsoft's playwright-mcp at this engine if you are already committed
to it, and precisely what that costs. The sentence about losing the seeded
profile is scoped to Microsoft's server by name, because it is not true of ours.

The engine README never mentioned either sibling. A reader who would rather
prompt than script had one hand-off, to the page above, which told them no
server existed. There is now a short block after Install with both one-liners,
and the Related projects section lists the three siblings before the eleven
third-party neighbours it already had.

Two smaller things the same audit turned up: the Python floor was stated only
as a badge image, about 200 lines below the install block a 3.10 user copies,
and the core's README described its second consumer as a desktop profile
manager, which was invisible_firefox, whose repository was deleted on
2026-08-18.

* One home for the download size, and the handle work in the changelog

Three READMEs carried a figure for the first-run download and no two agreed:
"about 700 MB" on both consumer pages, "~238 MB download (~544 MB unpacked)"
here. The seal packaged with invisible_core has the real numbers - 240 MB for
Windows, 262 and 253 for the two Linux legs - so all three were wrong, the
consumers by roughly triple.

A figure with three homes has no home. The consumers now say "a few hundred
megabytes" and point here; this file carries the per-platform numbers, taken
from the seal.

The changelog gains the ElementHandle entry under Unreleased. Nine acting
methods is a user-visible addition and the file exists to say so.

* Translate the identifiers the language gate cannot see

The gate reads prose - two Italian function words in a file - so a lone
identifier passes it. e2e-hunt.yml had `giri` as a workflow input and wrote its
artifacts under `prove/giri/giro_NN.log`, all of which the gate looked at and
found nothing wrong with, correctly.

The rule names workflow steps explicitly, so these are `runs` and
`evidence/runs/run_NN.log` now. Noting it because it is the shape of what the
gate misses, not a one-off: a name is not prose, and the check is for prose.
2026-09-03 13:12:02 +02:00
github-actions[bot] 430668e50f record 0.9.0 as published (#129)
The ledger entry for 0.9.0. Without it the next release is refused by
version_gate: the index would serve a version the ledger does not record.
2026-09-02 19:05:59 +02:00
208 changed files with 13894 additions and 1350 deletions

No files matched your search

+8 -8
View File
@@ -30,7 +30,7 @@ name: e2e hunt
on:
workflow_dispatch:
inputs:
giri:
runs:
description: "How many runs at most (at 12% it takes ~18 for a 90% chance)"
required: false
default: "18"
@@ -92,19 +92,19 @@ jobs:
- name: Loop until it catches one
env:
PYTHONUNBUFFERED: "1"
INVPW_TEST_WATCHDOG_FILE: prove/e2e-watchdog.log
INVPW_TEST_WATCHDOG_FILE: evidence/e2e-watchdog.log
run: |
set -u
runs="${{ inputs.giri }}"
mkdir -p prove/giri
# `prove/` inside the workspace, not RUNNER_TEMP: on Windows that
runs="${{ inputs.runs }}"
mkdir -p evidence/runs
# `evidence/` inside the workspace, not RUNNER_TEMP: on Windows that
# variable contains backslashes and does not cross bash reliably.
# xvfb only where it exists; on Windows the browser goes to the
# runner's desktop.
if [ "$RUNNER_OS" = "Linux" ]; then PRE="xvfb-run -a"; else PRE=""; fi
captured=0
for n in $(seq 1 "$runs"); do
log="prove/giri/giro_$(printf '%02d' "$n").log"
log="evidence/runs/run_$(printf '%02d' "$n").log"
t0=$(date +%s)
set +e
$PRE python -u scripts/run_e2e.py "$FF" > "$log" 2>&1
@@ -140,7 +140,7 @@ jobs:
with:
name: e2e-hunt-${{ inputs.os }}-${{ github.run_id }}-${{ github.run_attempt }}
path: |
prove/giri
prove/e2e-watchdog.log
evidence/runs
evidence/e2e-watchdog.log
if-no-files-found: warn
retention-days: 14
+23 -10
View File
@@ -13,7 +13,7 @@ name: firefox-launch-matrix
# cache is content-keyed (Cache/<tag>_<version>_<buildid>/), so every cell failed
# with NOT FOUND - a failure that looked exactly like the bug under investigation
# and was not. Nine red cells read as "reproduced everywhere". The path now comes
# from `python -m invisible_playwright path`, the only thing that knows it.
# from the last line of `fetch`, the command that verifies the sealed tree.
on:
workflow_dispatch:
@@ -82,23 +82,36 @@ jobs:
pip install .
- name: Fetch the sealed binary
run: python -m invisible_playwright fetch
shell: pwsh
run: |
$fetchOutput = @(python -m invisible_playwright fetch)
$fetchExit = $LASTEXITCODE
$fetchOutput | ForEach-Object { Write-Host $_ }
if ($fetchExit -ne 0) {
exit $fetchExit
}
$ffPath = [string]($fetchOutput | Select-Object -Last 1)
$ffPath = $ffPath.Trim()
if (-not $ffPath -or -not (Test-Path $ffPath)) {
Write-Error "fetch reported no firefox.exe at '$ffPath'"
exit 1
}
"FF_PATH=$ffPath" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
- name: Verify firefox.exe can launch standalone
shell: pwsh
run: |
# ASK for the path, never rebuild it. The cache directory is keyed on
# tag + base version + BuildID, so any string assembled here is a second
# copy of a naming rule that has already moved once - and when it drifts
# the step fails with NOT FOUND, which is indistinguishable from the
# launch bug this job exists to detect.
$ffPath = (python -m invisible_playwright path).Trim()
# CARRY the path from fetch, never rebuild it. The cache directory is
# keyed on tag + base version + BuildID, so any string assembled here
# is a second copy of a naming rule that has already moved once - and
# when it drifts the step fails with NOT FOUND, indistinguishable from
# the launch bug this job exists to detect.
$ffPath = $env:FF_PATH
Write-Host "Package reports: $ffPath"
if (-not $ffPath -or -not (Test-Path $ffPath)) {
Write-Error "firefox.exe NOT FOUND at '$ffPath' (reported by the package)"
Write-Error "firefox.exe NOT FOUND at '$ffPath' (reported by fetch)"
exit 1
}
"FF_PATH=$ffPath" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
Write-Host "Launching: $ffPath --version"
# NOTE: firefox.exe --version on Windows prints the version but may
# return non-zero exit code (sub-process fork quirk). Check stdout.
+99 -1
View File
@@ -20,6 +20,35 @@ concurrency:
cancel-in-progress: true
jobs:
# The gate was written FOR this repository on 2026-08-27, after 549 lines of
# Italian shipped here in one subsystem and 852 more were found in 33 files
# that were already public. It has been wired nowhere ever since: not into
# tests.yml, not into the pre-push hook, whose steps are pytest, pin, names,
# internals and publish. Both sibling packages copied the script AND the CI
# step; this one kept only the script, so the one repository the rule exists
# for is the one that never checked. Measured 2026-09-03, the first time
# anybody ran it here: four files, red.
#
# Its own job, and deliberately NOT behind core-on-index. Reading files needs
# no install, and hanging a language check off the availability of a package on
# an index would silently skip it during exactly the window when releases are
# being made.
english:
name: the repository is English
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: check the prose
# --selftest first: a language gate that has only ever printed "clean" is
# the same non-gate as any other, and this one can go blind from a single
# edit to its word list.
run: |
python scripts/check_english_only.py --selftest
python scripts/check_english_only.py
# `pip install -e ".[dev]"` below resolves `invisible-core==N.M.0` from the
# package index. The core is published BEFORE this package, so between the
# first push of this repo and that upload there is a window in which no
@@ -150,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:
@@ -159,10 +220,47 @@ 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
# FIFTEEN commits of different content on top of the tag - 39 files, 841
# insertions, the screenshot clip fix among them. A release from there would
# have published NOTHING and reported success, because publish.yml treats an
# already-present version as a deliberate no-op: right for a re-pushed tag,
# indistinguishable from somebody forgetting to bump. The fix could not have
# reached anybody, and nothing would have said so.
#
# Pull requests only: on main straight after a release the version IS the
# published one until somebody bumps, and a gate that is red at rest is one
# people learn to skip. Bumping publishes nothing - publishing happens on a
# tag push - so main on an unreleased version is the normal state between
# releases and the rule costs one line.
version:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
# The gate diffs the tree against the tag of the published
# version; a shallow clone has no tags and cannot tell.
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: the version this change proposes is still free
env:
IPW_CHECK_VERSION: "1"
run: |
python -m pip install --upgrade pip
pip install pytest
python -m pytest -q tests/test_version_is_not_taken.py
+5 -6
View File
@@ -49,10 +49,7 @@ jobs:
python -m pip install --upgrade pip
pip install -e ".[dev]"
- name: Fetch the patched Firefox binary
run: python -m invisible_playwright fetch
- name: Resolve binary path
- name: Fetch the patched Firefox binary and expose its path
shell: bash
run: |
# NOT `echo "VAR=$(cmd)" >> $GITHUB_ENV`. echo exits 0 whatever the
@@ -61,9 +58,11 @@ jobs:
# `pytest.skip("no patched binary")`, pytest exits 0, and the job is
# green having verified nothing - which is exactly what run #1 did.
set -euo pipefail
BIN="$(python -m invisible_playwright path)"
FETCH_OUTPUT="$(python -m invisible_playwright fetch)"
printf '%s\n' "$FETCH_OUTPUT"
BIN="$(printf '%s\n' "$FETCH_OUTPUT" | tail -n 1)"
if [ -z "$BIN" ] || [ ! -e "$BIN" ]; then
echo "invisible_playwright path returned '$BIN', which is not a" >&2
echo "invisible_playwright fetch returned '$BIN', which is not a" >&2
echo "file. Refusing to run a suite that would skip itself green." >&2
exit 1
fi
+198
View File
@@ -6,6 +6,204 @@ 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
- **The launch counter lives on the engine's repository.** Every session now
declares `invisible_firefox.usage_ping.url` through `invisible-core 27.18.0`,
pointing at the `usage-counter` release of `firefox_antidetect_patch`, the
repository that builds and ships the engine. The engine's compiled default
says the same from the next build. Engines older than firefox-21 do not read
the pref and are not counted. To opt out of the ping, set
`invisible_firefox.usage_ping.enabled` to `False` in `extra_prefs`.
- **The `browser launches` badge is back.** It was removed in 0.7.2 because the
counter behind it lived on a repository that had been deleted, so the badge
would have redrawn a frozen number every morning. The counter has lived on
this repository since 2026-08-19 and is counting again, so the figure the
badge shows is live. It is cumulative, and it undercounts: engines before
firefox-21 still ask the old address, and they rejoin only as they upgrade.
## [0.12.1] - 2026-09-05
### Fixed
- **A persistent profile keeps its cookies and storage for the next session.**
Since 0.8.0, `profile_dir=` kept nothing: the first session on a profile set a
cookie and a localStorage entry and read both back, the second session on the
same profile read an empty jar and `None`, and on disk `cookies.sqlite` held
zero rows. The persistent launch handed back an ordinary context, a Juggler
container with its own userContextId, and Juggler deletes a container's
cookies and storage together with the identity when the context is removed;
everything a session wrote lived in a container that died with the session.
The persistent context is now the browser's default one, the one whose state
is the profile's, addressed by omitting `browserContextId` and never removed;
closing it closes the browser, as upstream does. Found by a clean-environment
check of 0.12.0, on the day after the docs page promised "logging in once
instead of every run".
### Added
- **A test that a persistent profile keeps state**, e2e: two sessions on one
profile, cookie and localStorage written in the first and read in the second,
and the cookie row read from `cookies.sqlite` in between, so a regression
cannot pass by keeping the data where the page sees it and the disk does not.
Against 0.12.0 it fails on the on-disk read.
## [0.12.0] - 2026-09-04
### Fixed
- **The first launch on Windows works.** On a machine that had never run the
engine from that path, the first `InvisiblePlaywright(...)` exited with
`3221226505` (0xC0000409) before the protocol came up, and the second one
worked. It was Firefox's launcher process, not the browser: on a new path
`firefox.exe` runs as the launcher first and forwards the Juggler pipe to the
real browser, and it read that pipe from CRT descriptors 3 and 4, which the
Node.js driver provides and this client does not, since it names the handles
in `PW_PIPE_READ` / `PW_PIPE_WRITE`. The launcher died on `_get_osfhandle(3)`;
the next launch found a launcher timestamp with no browser timestamp in the
registry and disabled the launcher for that path, which is why it failed
exactly once per machine and why nothing about the cache directory mattered.
The engine is firefox-27, where the launcher forwards the handles it is
handed. Every Windows first launch since 0.8.0, the release where this client
replaced the Node driver, had this; the daily Windows install check had been
red since 2026-08-31. (#144)
### Added
- **A test for the first launch from a path Firefox has never run from**,
Windows only, e2e. It removes the launcher's registry values for the binary
under test, launches once, and checks both that the page answers and that the
launcher recorded a start followed by the browser's, so a success with the
launcher disabled, the path that always worked, does not pass. Against
firefox-26 it fails with the exit code above.
### Internal
- Engine pin moved to firefox-27 through `invisible-core 27.17.0`.
## [0.11.0] - 2026-09-04
### Fixed
- **A screenshot photographs where the page is.** The clip was
`{x: 0, y: 0, width: innerWidth, height: innerHeight}`, and that clip is in
document coordinates: not the window, but the top corner of the page at the
window's size. An agent that scrolled and looked got the same image every
time, and nothing in the image says so. `full_page` was not read at all:
800x600 came back where 800x4000 was asked for. (#136)
- **Two manual workflows stop calling the removed `path` command.** Both
called `python -m invisible_playwright path`, a subcommand removed when the
CLI became `fetch` plus `version`. The Windows launch matrix failed in all
three cells before reaching its launch probe, and the WebRTC gate had not run
since the removal. The existing parser gate scanned Python tests only, so
neither call site was in its perimeter; there is now one that reads the
workflows too. Thanks to @SamadhiFire for finding and fixing it. (#141)
### Added
- **A check that asks the index whether the version a change proposes is
still free**, on pull requests. This release exists partly because that
check found its own repository in the state it exists to prevent: 0.10.0 was
on the index while main sat on 0.10.0 with fifteen commits on top of the
tag, the screenshot fix among them. A release from there would have
published nothing and reported success, because the publish workflow treats
an already-present version as a deliberate no-op, which is right for a
re-pushed tag and indistinguishable from somebody forgetting to bump. (#142)
### Documentation
- Twelve pages stop shipping code that cannot run as pasted, tool metadata is
out of the shipped screenshots, and the front page names the agent layer
that sits on this engine. (#137, #138, #139, #140)
## [0.10.0] - 2026-09-03
### Added
- **Nine acting methods on `ElementHandle`.** `click`, `hover`, `fill`, `type`,
`press`, `focus`, `check`, `uncheck` and `select_option` now work on a handle,
so `page.query_selector("#go").click()` does what it does in Playwright. Until
now the driver served fourteen handle methods, every one of them a read, and
every action answered `ElementHandle has no method 'click'`.
They go through the same humanised path as the selector versions - approach,
hover, press, release, with the hit-target check and the actionability retry -
rather than a second, simpler one. Two click paths would be two fingerprints.
What differs is only what should: the node is not looked up again, and the
handle is still usable afterwards.
### Documentation
- **Two pages said there is no MCP server for this project.** Both were written
on 2026-07-27 and the server was published on 2026-08-19: true when written,
and afterwards they steered readers to Microsoft's server, which cannot carry
the seeded profile, for a problem ours solves. The integration page now opens
with ours and is what it actually is - how to point Microsoft's playwright-mcp
at this engine if you are already on it, and what that costs.
- **The README never mentioned either sibling.** A reader who would rather prompt
than script had one hand-off, to the page above, which told them no server
existed. There is now a short block after Install with both one-liners, and the
Related projects section lists the three siblings before the third-party ones.
- The Python floor was stated only as a badge image about 200 lines below the
install block, and the first-run download size disagreed across three READMEs,
all three wrong against the packaged seal. One home for it, here.
- Four wiki pages edited in a working tree on 2026-08-30, rescued onto a branch
and then lost a second time when the branch was never merged. Landed.
### Internal
- The English-only gate was written for this repository on 2026-08-27 and wired
nowhere: not into tests.yml, not into the pre-push hook. Both sibling packages
copied the script and the CI step; this one kept only the script. Run here for
the first time it found four Italian test files, now translated, and it runs in
CI from now on.
## [0.9.0] - 2026-09-02
### Fixed
+3322
View File
File diff suppressed because it is too large. Load diff
+48 -2
View File
@@ -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).
---
@@ -36,11 +44,27 @@ Once the browser is handled it stops being the variable. If you are still gettin
```bash
pip install invisible-playwright
python -m invisible_playwright fetch # one-time ~238 MB download (~544 MB unpacked), sha256-verified
python -m invisible_playwright fetch # one-time download, sha256-verified: 240 MB (Windows) / 262 MB (Linux x86_64) / 253 MB (Linux arm64), about 550 MB unpacked
```
Requires **Python 3.11 or newer**.
Supported platforms: **Windows x86_64**, **Linux x86_64 / arm64**. macOS is no longer supported (releases stopped at firefox-20); on a Mac the package refuses at launch with a clear message rather than downloading a binary that no longer exists.
### If you would rather prompt than script
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 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).
Same engine underneath, and the second is a client of the first.
---
## Usage
@@ -183,6 +207,16 @@ is the map most other pages link back to, [Playwright detected as a bot on one s
is the troubleshooting order, and [navigator.webdriver is not the tell you think it is](docs/navigator-webdriver-explained.md)
explains the most famous property in this space and why patching it alone buys you
almost nothing.
The detectors section now covers the commercial anti-bot products by name, each
read from its own documentation or from confirmed reverse engineering:
[Cloudflare Bot Management](docs/cloudflare-bot-management-explained.md) and
[Turnstile](docs/cloudflare-turnstile-explained.md),
[DataDome](docs/datadome-explained.md), [Kasada](docs/kasada-explained.md),
[Akamai Bot Manager](docs/akamai-bot-manager-explained.md),
[PerimeterX](docs/perimeterx-explained.md), [hCaptcha](docs/hcaptcha-explained.md),
[Imperva](docs/imperva-incapsula-explained.md), and
[the rest of the set](docs/guides-detectors-explained.md).
- [crawl4ai stealth and custom browser engines](docs/crawl4ai-stealth-custom-browser.md) - browser_type accepts firefox but there is no executable_path; where the adapter seam is
- [Why headless browsers render different fonts](docs/headless-fonts-differ.md) - the three causes, the per-platform font sets, and why the fix is not installing more fonts
- [How to make Linux and macOS report real Windows fonts](docs/bundled-fonts-cross-platform.md) - one manifest, three font backends convinced not to ask the host, and the four seams still open
@@ -197,7 +231,18 @@ almost nothing.
## Related projects
The open-source neighbours, and what each one is for.
**The other pieces of this one.** The engine is the middle of three, and the
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.
- **[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.
**On the Firefox side**
@@ -245,5 +290,6 @@ This project is for educational purposes only. It is provided as-is, with no war
<a href="https://github.com/feder-cr/invisible_playwright/blob/main/LICENSE"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/license.svg" alt="License: MIT"></a>
<a href="https://www.python.org/downloads/"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/python.svg" alt="Python 3.11+"></a>
<a href="https://github.com/feder-cr/firefox_antidetect_patch/releases"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/firefox.svg" alt="Firefox 151.0"></a>
<img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/badges/docs/badges/launches.svg" alt="browser launches">
<a href="https://github.com/feder-cr/invisible_playwright/stargazers"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/badges/docs/badges/stars.svg" alt="GitHub stars"></a>
</p>
+3 -3
View File
@@ -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.
+11 -208
View File
@@ -1,6 +1,6 @@
---
title: "AI agent retry loops trip rate limits, not fingerprints"
description: "Why AI agent retry loops multiply requests into a volume signal that trips rate limits, and why throttling belongs in the agent loop, not the browser engine."
description: "Retry and re-plan loops multiply requests into a volume signal; throttling belongs in the agent loop. This page moved to the AIHawk wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 17
@@ -9,213 +9,16 @@ nav_order: 17
# AI agent retry loops trip rate limits, not fingerprints
An agent that gets a browser to look like a real person will still get blocked if it
asks for a page thirty times in ten seconds. That block has nothing to do with the
fingerprint. It is a counter.
This page moved to the AIHawk wiki, where the agent-experience content now
lives:
This page is about the failure mode that a perfect disguise does not touch: an agent
retries and re-plans on failure, every retry is another request, and a stack of retries
per second is a volume and behaviour signal that trips rate limits and quotas long
before any fingerprint check runs. The fix does not live in the browser. It lives in
the loop that drives it.
**[Agent retry loops trip rate limits, not fingerprints](https://github.com/feder-cr/AIHawk/wiki/agent-retry-loops-rate-limits)**
## Why an agent makes more traffic than a scraper
The one-paragraph version: an agent that retries and re-plans multiplies its
requests, and volume is scored server-side against your address and account.
No browser property changes a request count. Throttle in the loop that
produces the requests.
A hand-written scraper visits a known list of URLs once. An agent does not. It observes
a page, decides a next action, acts, and when the action fails it re-plans and tries
again. That control loop is the whole point of an agent, and it is also a request
multiplier.
Three things stack up:
- **Retries.** A transient error, a slow load, a missing element, and the agent tries
the same step again. One logical action becomes three or five HTTP requests.
- **Re-planning.** When a step fails the agent often re-reads the page, or reloads it,
or navigates back and forward to re-orient. Each of those is a fresh visit to a URL a
human would have loaded once.
- **Exploration.** An agent that does not know the site's layout probes it: opens a
page to see what is there, backs out, opens another. A person who knows what they want
does not.
The result is that a single high-level task ("find the price of item X") can produce
ten or twenty page loads, most of them to the same few URLs, in a burst measured in
seconds. That pattern is trivial to count, and counting is exactly what a rate limiter
does.
## Rate limits read volume, not the browser
A fingerprint check and a rate limit answer two different questions, and a convincing
disguise only answers one of them: one asks whether this browser is real, the other only
counts how many requests just arrived.
A fingerprint check reads properties of the browser: the GPU string, the canvas hash,
the font list, the TLS handshake. It asks "is this a real browser". invisible_playwright
is built to make that answer yes, which is why it passes most of that class of check:
the engine is a genuine Firefox patched at the C++ level, so the values are real rather
than spoofed on top of a headless build.
A rate limit reads something completely different: how many requests arrived from this
address, this account, or this session, in this window. It does not open the browser at
all. It increments a counter and compares it to a threshold. The request could come from
the most convincing browser ever built and the counter would go up by exactly one.
So the two defences are orthogonal:
| Signal | What it reads | Does a real-looking browser help |
|---|---|---|
| Fingerprint / driver / TLS | Properties of the client | Yes - this is what the engine is for |
| Rate limit / quota | Count of requests over time | No - N requests is N requests |
| Per-account quota | Actions tied to one identity | No - the account is the unit, not the browser |
| Behaviour / velocity | Timing and shape of the traffic | No - the loop decides the timing |
The bottom three rows are not something an engine can fix, because the engine only
controls what one request looks like, not how many of them you send or how fast. That is
a property of the loop.
## Put the budget in the loop, not the engine
The consequence is a design rule: **backoff, throttling and a request budget belong in
the agent loop.** No browser setting throttles an agent that has been told to retry
until it succeeds.
Three controls cover most of it:
- **Exponential backoff on retry.** When a step fails, wait, and wait longer each time,
instead of retrying immediately. A failed request answered by an instant identical
request is the clearest velocity signal there is.
- **A hard request budget.** Cap the number of requests per task and per unit of time.
When the budget is spent, stop and surface the failure rather than letting the loop
spend the site's patience for you.
- **A cap on re-plans.** Bound how many times the agent may re-read or reload the same
URL before it gives up. An unbounded re-plan loop is an accidental refresh storm.
The unit to think in is requests per minute from one address and one account, not
requests per browser. Ten agents behind one exit IP each politely pacing themselves are,
to the counter, one very busy client.
## A retry loop that backs off
Here is the two-line launch plus a retry wrapper that carries a budget and backs off.
The browser is a stealth Firefox; the throttling is plain Python, because that is where
it has to be.
```python
import time
from invisible_playwright import InvisiblePlaywright
def fetch_with_budget(page, url, *, max_attempts=4, budget):
"""Load url with exponential backoff. Raises when the budget is spent."""
for attempt in range(max_attempts):
if budget["spent"] >= budget["limit"]:
raise RuntimeError("request budget exhausted; stopping instead of retrying")
budget["spent"] += 1
try:
page.goto(url, wait_until="domcontentloaded")
return page
except Exception:
if attempt == max_attempts - 1:
raise
backoff = 2 ** attempt # 1s, 2s, 4s, ...
time.sleep(backoff)
return page
budget = {"spent": 0, "limit": 30} # hard cap for the whole task
with InvisiblePlaywright(seed=42) as browser:
page = browser.new_page()
fetch_with_budget(page, "https://example.com", budget=budget)
# ... agent observes, decides, acts; every navigation goes through the budget
```
The `browser` returned is a real Playwright
[`Browser`](https://playwright.dev/python/docs/api/class-browser), so every standard
method works unchanged - `new_page`, `goto`, `click`, `wait_for_selector`. The stealth is
in the engine; the pacing is in `fetch_with_budget`. Nothing about `seed=42` slows the loop
down, and nothing about the loop changes the fingerprint. They are separate jobs.
Pacing the actions themselves matters too, because uniform, machine-fast timing is its
own tell independent of volume. That is the subject of
[the pause shaped like model latency](ai-browser-agents-stealth.md), and it is worth
reading alongside this page: one is about how many requests, the other about their
shape.
## What invisible_playwright fixes, and what it does not
The honest split, because overclaiming here is both wrong and a way to get someone
blocked while they trust a promise that was never true.
**What the engine handles.** The fingerprint, driver and TLS layers read as a genuine
Firefox, so the class of check that asks "is this a real browser driven by a real
person" mostly answers yes. That is measurable: on the public tampering suites a session
comes back internally consistent rather than flagged, and the same seed produces the
same machine every run so a failure is reproducible.
**What you supply.** The engine does not change your IP's reputation, it does not create
per-account quota out of nothing, it does not slow your loop down, and it does not shape
your timing. Those are yours to bring:
- A clean exit, because a real-looking browser on a
[datacenter IP is still on a datacenter IP](can-websites-detect-a-datacenter-proxy-ip.md),
and a counter on the address does not care how good the browser is.
- Human pacing, from the loop, using the controls above.
- Respect for the account's own limits, which are counted against the identity and not
the browser.
Put plainly: invisible_playwright makes each request look like it came from a real
person. It does not make a thousand requests look like one. That second job is the
loop's, and no engine setting will do it for you. When a clean fingerprint still gets
blocked, volume and address are the usual reasons -
[which is a page of its own](why-blocked-with-a-clean-fingerprint.md).
## Conclusion
Retries and re-planning are what make an agent an agent, and they are also what turn one
task into a burst of requests. A burst is counted, and a counter is a different defence
from a fingerprint check: the most convincing browser in the world still increments it by
one per request. So the throttle cannot live in the engine. Give the loop a budget, back
off on failure, cap the re-plans, and put a clean exit under it. The browser's job is to
make each request real; keeping the requests few and well-spaced is yours.
## Short answers to the questions that lead here
**Will a stealth browser stop my agent from being rate limited?** No. Rate limits count
requests; they do not inspect the browser. A real-looking fingerprint helps with
detection, not with volume.
**Why does my agent get blocked when a manual visit works fine?** Almost always because
the agent sent many more requests, much faster, than the person did. Retries and reloads
multiply traffic that a human never generates.
**Where should backoff and throttling live?** In the agent loop, not the engine. No
browser setting paces an agent that was told to retry until it succeeds.
**Does the seed or fingerprint affect how fast I can go?** No. The seed controls the
identity, not the timing. Speed and request count are decided entirely by your loop.
**Is a per-account quota a fingerprint problem?** No. A quota is counted against the
identity or the account, not the browser, so a better fingerprint does nothing for it.
Budget the actions instead.
**How many requests per minute is safe?** There is no universal number; it depends on
the site. The safe habit is a hard budget per task and per window, plus backoff, so a
failing loop stops itself rather than accelerating.
## Sources
- This project's own velocity flag, raised against invisible_playwright during testing,
which turned out to be the test harness hammering one scoring endpoint from one
address - the same volume signal described here, produced by our own gate.
- The wrapper's documented API (`InvisiblePlaywright`, seed reproducibility, a real
[Playwright `Browser`](https://playwright.dev/python/docs/api/class-browser) return)
as shipped, used verbatim in the example above.
**See also:** [the pause shaped like model latency](ai-browser-agents-stealth.md) for
the timing side of the same problem, [how to rate limit your scraper](how-to-rate-limit-your-scraper-playwright.md)
for the pacing mechanics in detail, and [what actually detects an agent](browser-use-detection.md)
across the layers a fingerprint does not cover.
---
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
a Firefox patched at the C++ level driven by stock Playwright. The velocity flag that
started this page was ours, and it belonged to the harness, not the browser.*
Related mechanism pages that stay on this wiki:
[why you can be blocked with a clean fingerprint](why-blocked-with-a-clean-fingerprint.md)
and [ASN and IP reputation in bot detection](asn-and-ip-reputation-in-bot-detection.md).
+13 -216
View File
@@ -1,6 +1,6 @@
---
title: "Why AI browser agents have their own timing signal"
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. Where pacing and dwell time live in your code."
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. This page moved to the AIHawk wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 10
@@ -9,221 +9,18 @@ nav_order: 10
# Why AI browser agents have their own timing signal
A stealth engine can make your browser read as a genuine Firefox down to the TLS
handshake, and an AI agent driving it can still stand out for a reason that has nothing
to do with the browser at all: the rhythm of the loop that controls it.
This page moved to the AIHawk wiki, where the agent-experience content now
lives:
An LLM agent runs a think-act cycle. It looks at the page, decides on an action, emits
the action, waits for the result, and looks again. That cycle has a shape, and the shape
is measurable. The gaps between actions cluster around the model's latency, the actions
themselves land effectively instantly, and the pointer arrives at each target without a
human's approach, overshoot or correction. None of that is in the fingerprint. It is a
separate signal, orthogonal to every value a fingerprinting page reads, and a site can
check it on its own.
**[The timing signal AI agents give off](https://github.com/feder-cr/AIHawk/wiki/ai-agent-timing-signal)**
This page is about that signal: what produces it, why a clean fingerprint does not
touch it, and where the fix has to live, which is in your code and not in the engine.
The short version it still owes you here: a think-act loop pauses for model
latency, and that pause repeats with a regularity no human produces. The
pointer arc between actions is the engine's job, and this engine humanises it;
the step-to-step rhythm is produced by the agent loop, which no fingerprint
work reaches.
## What the timing signal actually is
Behaviour is a fingerprint of a different kind. A fingerprinting page reads static
properties: the GPU string, the font list, the canvas hash. A behavioural check reads
the stream of events a session produces over time: when clicks happen relative to each
other, how a pointer travels between two points, how long a value takes to type, whether
anything is read before it is acted on.
A human session is full of small irregularities. There is a pause to read that varies
from a second to several. The pointer curves toward a target, arrives a little off, and
corrects. Typing has an uneven cadence with the occasional longer gap. Time is spent on
the page doing nothing measurable.
An agent loop, left to its own timing, produces almost none of that. The interesting
part is that this is true even when the engine underneath is perfect, which is what makes
it worth a page of its own.
## Why a perfect fingerprint does not touch it
invisible_playwright is designed to look like a real browser driven by a real person, and
that is why it passes most detection checks: the engine fingerprint, the TLS handshake and
the driver layer all read as a genuine Firefox rather than an automated one. That is a real
result and it is most of what people are blocked for.
It is also not everything. The same honesty that makes the product worth using means being
clear about the edges: on its own it does not fix IP reputation, per-account quotas, rate
limits, or behaviour. Those are supplied by you, a clean exit and human pacing among them.
The timing signal is squarely in that last category. The engine controls what the browser
*is*; it does not control the cadence at which your loop decides to act, because that cadence
is produced above the browser, in the code that calls it.
Put differently: a fingerprint is a photograph and behaviour is a motion study. Making the
photograph perfect does nothing to the motion study, and the two are read by different parts
of a detection system. This is the same reason the [testing method that catches false
passes](how-to-test-bot-detection.md) lists behaviour among the things no in-page suite
covers.
## What the loop leaks: gaps and pointer jumps
Two specifics, because they are the ones an agent produces without meaning to.
**Inter-action gaps that cluster.** Between one action and the next sits a wait for the
model to respond. That wait is not random the way a human pause is; it clusters around
whatever the model's latency happens to be, run after run. A distribution of gaps that is
tight and repeatable, rather than the broad, ragged spread a person produces, is itself the
tell. It does not matter that the individual number looks plausible. The *shape* of the
distribution is the signal.
**Actions that land instantly, and pointers that jump.** When an agent decides to click a
coordinate, the naive path is to dispatch the click at that coordinate with no travel and
no dwell. The pointer teleports from wherever it was to the target, and the action fires
with zero read time in front of it. A form filled field by field with no gaps, a click on
an element the instant it appears, a pointer that never passes through the space between two
targets: each is a motion no hand produces. The [detected-on-one-site checklist](playwright-detected-as-bot.md)
reaches this at step five, after the machine and the automation tells, because it is what is
left once the browser itself is clean.
invisible_playwright does smooth one piece of this for you: a click arcs the pointer to the
target on a Bezier curve rather than teleporting, so an individual click's *path* is
human-shaped. What it cannot smooth is the *cadence* between your actions and the dwell time
in front of them, because your loop, not the browser, decides when the next action happens.
## Pacing and pointer motion live in your code, not the engine
The consequence is a division of labour, and it is a clean one.
The engine owns the browser identity: the fingerprint, the TLS layer, the driver surface.
You own the rhythm: how long to dwell before acting, how much to vary the gap between
actions, whether to read the page before touching it. No engine can supply the rhythm for
you, because the rhythm is produced by the loop calling the engine, and that loop is yours.
Concretely, that means adding pacing and dwell to the code between your actions rather than
expecting the browser to add it underneath. Here is the minimal shape, using the real
two-line launch and standard Playwright methods on the returned browser:
```python
import random
import time
from invisible_playwright import InvisiblePlaywright
def dwell(low=0.6, high=2.4):
"""A varied pause, the kind reading and deciding actually produces."""
time.sleep(random.uniform(low, high))
with InvisiblePlaywright(seed=42) as browser:
page = browser.new_page()
page.goto("https://example.com")
dwell(1.2, 3.0) # read before acting, not act on arrival
page.click("#open") # the engine arcs the pointer on a Bezier curve
dwell()
for ch in "a search phrase": # per-key rhythm, not one instant fill
page.keyboard.type(ch)
time.sleep(random.uniform(0.04, 0.19))
dwell()
page.click("#submit")
```
The `browser` returned by `InvisiblePlaywright` is a real Playwright `Browser`, so every
method is the one you already know; the `seed=42` makes the identity reproducible so a run
that gets flagged can be replayed exactly. The only thing added above the plain automation is
the pacing, and that is the point: it has to be added, because it is the part the engine
cannot produce for you.
A note on doing it well. Uniform delays are their own tell. `time.sleep(1.0)` between every
action just moves the cluster from "instant" to "exactly one second", and a tight cluster at
one second is as machine-regular as a tight cluster at zero. Vary the pauses, make them
depend on what the step is doing (a long read before a decision, a short gap between two
keystrokes), and avoid the same number twice. The goal is the ragged, context-dependent
spread a person produces, not a constant with a label on it.
## Measuring your own rhythm before a site does
You can read this signal off your own agent the same way a site would, which is the honest
way to know whether your pacing is doing anything. Record a timestamp at each action, then
look at the distribution of the gaps.
```python
import time
timestamps = []
def mark():
timestamps.append(time.monotonic())
# call mark() immediately before each page action, then afterward:
gaps = [b - a for a, b in zip(timestamps, timestamps[1:])]
print("count:", len(gaps))
print("min / max:", round(min(gaps), 3), round(max(gaps), 3))
print("mean:", round(sum(gaps) / len(gaps), 3))
```
If the min and max are close together, or the mean sits right on top of your model's
typical response time, your loop is emitting the clustered distribution described above and
the pacing is not varied enough yet. A human trace has a wide spread and a long tail. This is
the same instinct as reading the fingerprint report field by field rather than trusting a
verdict: measure the actual stream, do not assume the shape. For the related case of an agent
whose pauses line up with tool latency in a devtools context, see
[timing detection through the debugger](debugger-timing-detection.md).
## Conclusion
The engine fingerprint and the agent's rhythm are two different signals, read by two
different parts of a detection system, and a stealth browser addresses the first and not the
second. invisible_playwright makes the browser read as a genuine person's Firefox, which is
why it clears most checks; the cadence of your think-act loop is produced above the browser,
so pacing, dwell time and read-before-act have to live in your own code. Add them
deliberately, vary them so they are not merely a slower constant, and measure your own trace
the way a site would. That is the honest division of labour, and it is the one that holds up.
## Short answers to the questions that lead here
**Does a stealth browser hide that I am an AI agent?** It hides that the browser is
automated. It does not hide the rhythm of your control loop, which is a separate signal you
produce above the browser.
**What is the timing signal, exactly?** The gaps between your actions cluster around the
model's latency instead of spreading like a human's pauses, and actions land instantly with
pointers that jump straight to targets. Both are visible without reading any fingerprint.
**Can invisible_playwright fix my pacing for me?** No, and no engine can. It smooths an
individual click's pointer path on a Bezier curve, but the cadence between actions is decided
by your loop, so pacing and dwell have to live in your code.
**Do I just add a fixed sleep between actions?** That helps with "instant" but creates a new
tell: a tight cluster at one second is as regular as a tight cluster at zero. Vary the pauses
and make them depend on the step.
**Will fixing the timing get me past everything?** No. Behaviour is one signal among several.
A clean rhythm on a bad IP, over quota, or against a rate limit still fails; those are yours
to supply too, a clean exit and sane request volume among them.
**How do I know if my rhythm looks robotic?** Record a timestamp at each action and look at
the spread of the gaps. If min and max are close, or the mean sits on your model's response
time, the distribution is too tight.
## Sources
- This project's own testing notes, which list behaviour and the pause shaped like model
latency among the things no in-page suite covers.
- Standard Playwright's documented [`Browser`](https://playwright.dev/python/docs/api/class-browser),
[`Page`](https://playwright.dev/python/docs/api/class-page) and
[`Keyboard`](https://playwright.dev/python/docs/api/class-keyboard) methods, used unchanged
on the browser this wrapper returns.
- The behavioural step of this set's detected-on-one-site checklist, which reaches pointer
motion and typing cadence after the browser itself is clean.
**See also:** [what fits and what does not for AI browser agents](ai-browser-agents-stealth.md),
[why a CDP-driven agent has a tell of its own](browser-use-detection.md), and
[testing bot detection without a false pass](how-to-test-bot-detection.md).
---
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
a Firefox patched at the C++ level driven by stock Playwright. The engine makes the browser
real; the rhythm is yours to write, and this page is the part I keep having to add back into
my own agent loops.*
The mechanism layer stays on this wiki:
[mouse-dynamics behavioural biometrics](mouse-dynamics-behavioural-biometrics.md),
[keystroke timing detection](keystroke-timing-detection-playwright.md), and
[human-like mouse movement](human-mouse-movement.md).
+16 -5
View File
@@ -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
@@ -213,11 +213,22 @@ Chromium build.
differently about the GPU, the fonts, the audio device and the screen. The agent is
identical.
**How do you make an AI agent undetectable?** You do not, as a single setting. Three
separate problems each need their own fix: the engine fingerprint (what patching Firefox
at the C++ level answers), the machine surfaces a container gives away regardless of
engine (GPU, fonts, audio, screen), and the agent loop's own rhythm, which no fingerprint
patch touches. Fixing only the first and calling the agent undetectable is the mistake
this whole page is about.
**Which AI agent framework is most stealth-friendly?** The question is usually the wrong
one. Pick on the agent loop, then fix the machine, then consider the engine.
**Is there any agent route to an engine-level fingerprint?** MCP, through Microsoft's own
Playwright MCP server, which takes a browser and an executable path.
**Is there any agent route to an engine-level fingerprint?** Two, and they are not
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
identity.
**See also:** [browser-use in detail](browser-use-detection.md),
[crawl4ai in detail](crawl4ai-stealth-custom-browser.md),
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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.
+2 -2
View File
@@ -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
@@ -80,6 +80,15 @@ import re
import ssl
import time
def extract_text(msg):
# the plain-text part of a possibly multipart message
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == "text/plain":
return part.get_payload(decode=True).decode(errors="replace")
return ""
return msg.get_payload(decode=True).decode(errors="replace")
def fetch_code_from_inbox(sent_at, timeout_s=60, poll_every_s=2):
ctx = ssl.create_default_context()
deadline = time.time() + timeout_s
@@ -135,6 +135,8 @@ target application's enrollment page shows different values, in an advanced setu
screen or in the raw `otpauth://` URI, pass them explicitly:
```python
import hashlib
totp = pyotp.TOTP(secret, digits=8, digest=hashlib.sha256, interval=60)
```
+6 -6
View File
@@ -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 roughly 1,400 verified bots (AWS calls this "Akamai-style" verification the same idea by a different name; 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.
@@ -70,7 +70,7 @@ Several rule families sit entirely outside what any browser engine can affect. `
**What is token reuse, and why does it matter?** The same proof-of-legitimacy token appearing across multiple IPs, countries, or ASNs within a five-minute window. It is a detection axis with no browser-level answer, because it scores how a token is being shared, not what any individual session's browser does.
**Does Bot Control block search engines and other known-good bots?** No. AWS maintains a verified-bot list (~1,400 entries) that gets labeled and passed rather than blocked, and a newer cryptographic mechanism, Web Bot Authentication, lets a bot sign requests to prove its identity instead of being challenged.
**Does Bot Control block search engines and other known-good bots?** No. AWS maintains a verified-bot list that gets labeled and passed rather than blocked, and a newer cryptographic mechanism, Web Bot Authentication, lets a bot sign requests to prove its identity instead of being challenged.
**Does a real browser engine defeat AWS WAF Bot Control?** It answers the automation-signature and browser-consistency rules honestly, which removes that whole failure class. It has no bearing on IP/data-center signals, token-reuse-across-sessions rules, or the ML-based coordinated-activity detection, all of which operate above the level of any single browser.
+3 -3
View File
@@ -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.
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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 |
|---|---|---|---|
+14 -177
View File
@@ -1,6 +1,6 @@
---
title: "browser-use gets detected: what you can and cannot change"
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change, what stays out of reach on a server, and the timing tell specific to AI agents."
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change and what stays out of reach. This page moved to the AIHawk wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 2
@@ -9,182 +9,19 @@ nav_order: 2
# browser-use gets detected: what you can and cannot change
If your browser-use agent works locally and gets challenge pages on a server, the
problem is usually not the agent and not the prompt. It is the browser it drives and the
machine it runs on, and only some of that is reachable from configuration.
This page moved to the AIHawk wiki, where the agent-experience content now
lives:
This page is what `BrowserProfile` actually exposes, what those settings fix, what stays
out of reach, the signal that is specific to agent-driven sessions, and the honest answer
about swapping in a different engine.
**[browser-use getting blocked: what you can and cannot change](https://github.com/feder-cr/AIHawk/wiki/browser-use-getting-blocked)**
## What browser-use gives you to change
The unchanged short answer: browser-use exposes a real set of levers
(`executable_path`, `user_data_dir`, `proxy`, `headless`, `args`), all of
them Chromium-family, and none of them reaches the machine underneath - the
GPU, fonts, audio and screen a server answers with. A stealth-patched Firefox
is not a drop-in for its CDP driver; the route that accepts a different
engine is MCP.
browser-use's `BrowserProfile` lets you change six things: which browser binary
launches, its channel, a persistent profile directory, proxy, headless mode, and extra
command-line arguments. Everything else about the browser and the machine it runs on is
out of its reach. These fields are read from `browser_use/browser/profile.py`, the
configuration surface:
| Field | What it does |
|---|---|
| `executable_path` | which browser binary to launch |
| `channel` | a Chromium channel |
| `user_data_dir` | a persistent profile directory |
| `proxy` | proxy settings for the session |
| `headless` | headless or headed |
| `args` | extra command-line arguments |
That is a real set of levers, and three of them matter more than people use them for.
### executable_path, and what it expects
`executable_path` exists, and it expects a **Chromium-family** browser. The surrounding
code in `browser_use/browser/chrome.py` is entirely Chrome logic: finding a Chrome
executable, deriving the Chrome user-data directory from it, enumerating Chrome profiles.
The channel type is a Chromium channel.
The practical use of that field is pointing at your **real installed Chrome** rather
than the bundled Chromium. [Those are not the same browser](chromium-is-not-chrome.md):
the codec set differs, the branding differs, and a real Chrome install is a far more
common thing to be than a bundled test build.
### user_data_dir, which is underused
Pointing this at a profile that has genuinely been used is the single highest-value
change available in the configuration, because it is the only one that addresses history
rather than hardware.
An agent session starting from an empty profile is a browser that has never been
anywhere, which is
[most of why a fresh browser scores badly](recaptcha-v3-score.md). The traps that come
with persistent profiles are covered separately in
[what a persistent profile fixes and breaks](persistent-profiles.md), and the pairing
rule there applies here too.
## What configuration cannot reach
Everything about the machine. None of the fields above changes any of these, and on a
server all of them are true at once:
- **No GPU**, so WebGL reports a software renderer.
[What those strings mean](webgl-renderer-strings.md).
- **A container font set** that does not match the claimed platform.
[Why installing more is not the fix](headless-fonts-differ.md).
- **No audio device**, so the audio values fall back to defaults.
[The seven values](audiocontext-fingerprinting.md).
- **A screen with no taskbar** and a default resolution.
[The relationships that have to hold](screen-size-headless-tells.md).
- **Codec support** that describes a slim build rather than a desktop install, including
whether decoding is hardware accelerated.
[Three surfaces in one API](codec-fingerprinting.md).
- **A TLS handshake** decided before any of this by the network stack.
[Which no page-level layer can touch](ja3-ja4-tls-fingerprint.md).
This is why "it works on my laptop and not in Docker" is the most common shape of the
problem. The agent is identical; the machine is not.
[The container version of this list](playwright-docker-detection.md) goes through it in
order.
## The tell that is specific to agent-driven sessions
The tell specific to agent-driven sessions is timing, not fingerprint: an agent pauses to
think between actions, and those pauses cluster around model latency in a shape that human
reading never produces. This part does not apply to ordinary scraping and does apply to
browser-use.
An agent thinks between actions. It reads the page, calls a model, waits for a response,
then acts. That produces
[an interaction rhythm with a very particular shape](ai-agent-timing-signal.md):
- **Long, similar pauses before each action**, clustered around model latency rather than
around reading speed.
- **No movement during the pause.** A person reading a page moves the pointer, scrolls
slightly, drifts. An agent's pointer is perfectly still for two seconds and then
arrives exactly on a button.
- **Actions that land dead centre** on their targets, because coordinates come from the
accessibility tree rather than from a hand.
- **No wasted actions.** People scroll past things, hover over what they do not click,
and change their minds.
None of that is fixed by a stealth setting, and it is worth knowing because it explains
blocks that arrive **after** a few interactions rather than at the first page load. That
timing is the diagnostic:
[a block at first load points at the fingerprint or the address, a block after an
interaction points at behaviour](playwright-detected-as-bot.md).
## Can I use a stealth-patched Firefox with browser-use?
No, and it is better to say so plainly than to publish a workaround that does not work.
browser-use drives its browser over the Chrome DevTools Protocol, with Chrome-specific
arguments and Chrome profile handling. A Firefox binary in `executable_path` is not a
drop-in: the driver would be speaking a protocol the browser does not implement.
If you specifically want an engine whose fingerprint is set in its own source, the route
that works for agents is a different driver. Microsoft's
[`playwright-mcp`](https://playwright.dev/docs/getting-started-mcp) accepts a browser
and an executable path and speaks MCP, so an agent framework that talks MCP can drive a
patched Firefox through it.
[That integration is written up here](integrations/playwright-mcp.md).
That is a genuine trade: you give up browser-use's agent loop and get an engine-level
fingerprint. Which one matters depends on whether your blocks are arriving because of the
browser or because of the behaviour, and the timing test above tells you which.
## Conclusion
browser-use exposes enough configuration to fix the two things configuration can fix:
which browser binary runs, and whether the profile has a past. Point it at a real Chrome
and at a profile that has been used, and you have taken the available wins.
Everything else divides into two piles. The machine-level tells are shared with every
other automation tool and are fixed by changing the machine or the engine, neither of
which is a browser-use setting. The agent-rhythm tells are specific to this class of tool
and are not fixed by any fingerprint work at all.
Knowing which pile you are in takes one experiment: note whether the block arrives at the
first request or after a few actions.
## Short answers to the questions that lead here
**Why does my browser-use agent get blocked on a server but not locally?** Because the
server has no GPU, few fonts, no audio device and a default screen, and the agent is
identical in both places.
**Can I set a custom browser in browser-use?** Yes, `executable_path` in
`BrowserProfile`, and it expects a Chromium-family browser. Pointing it at your real
Chrome rather than the bundled Chromium is worth doing.
**Can I use a stealth Firefox with browser-use?** No. It drives over CDP, which Firefox
does not implement in the way the driver expects.
**Does a persistent profile help?** Yes, more than most settings, because it is the only
one that addresses having no history. Read the traps first.
**Why do blocks arrive after a few actions rather than immediately?** That usually points
at behaviour rather than fingerprint, and agent pacing has a recognisable shape.
**Does adding a proxy fix it?** It changes where you come from. If the browser is
announcing a datacenter through its GPU and fonts, the address was not the problem.
**See also:** [the checklist for being detected on one site](playwright-detected-as-bot.md),
which is the order to work in,
[Playwright in Docker](playwright-docker-detection.md), for the server case, and
[Playwright MCP](integrations/playwright-mcp.md), for the agent route that does accept a
different engine.
## Sources
- `browser_use/browser/profile.py`, which defines the configuration fields listed above,
and `browser_use/browser/chrome.py`, which is the Chrome executable and profile
handling. Read 2026-07-27.
- [Playwright's own MCP documentation](https://playwright.dev/docs/getting-started-mcp),
which lists `firefox` among the supported `--browser` values, confirming that route
(unlike browser-use) is not Chromium-only. Read 2026-08-06.
- The machine-level surfaces are each documented on their own page, linked above.
---
*From the notes of [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
a Firefox patched at the C++ level. This page says our engine does not fit browser-use,
because it does not, and a guide claiming otherwise would waste your afternoon.*
The mechanism layer stays on this wiki:
[Playwright in Docker and the datacenter machine](playwright-docker-detection.md),
[WebGL renderer strings](webgl-renderer-strings.md), and
[why headless fonts differ](headless-fonts-differ.md).
+1 -1
View File
@@ -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
+9 -9
View File
@@ -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.*
+4 -4
View File
@@ -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
+188
View File
@@ -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.*
+1 -1
View File
@@ -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
+2
View File
@@ -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.
+15 -188
View File
@@ -1,6 +1,6 @@
---
title: "Computer-use agents and browser fingerprint detection"
description: "Computer-use agents click by pixel, not DOM, so driver flags are moot for them. Engine fingerprint and action rhythm remain the detectable signals."
description: "Clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. This page moved to the AIHawk wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 6
@@ -9,193 +9,20 @@ nav_order: 6
# Computer-use agents and browser fingerprint detection
A computer-use agent (CUA) does not read the DOM to decide where to act. It takes a
screenshot, sends the image to a vision model, gets back a pixel coordinate, clicks
there, and takes another screenshot. That loop is the whole architecture of OpenAI's
Computer-Using Agent and of Anthropic's computer-use tool, and it changes which
detection signals matter and which stop mattering.
This page moved to the AIHawk wiki, retargeted at the question people
actually search:
This page is about that shift: why the automation flags people usually worry about are
moot for a coordinate agent, what is still checkable underneath it, and where
invisible_playwright helps and where you still have to do the work yourself.
**[Claude computer use detected as a bot](https://github.com/feder-cr/AIHawk/wiki/claude-computer-use-detected-as-bot)**
## Why the driver flags stop mattering
The core of it, kept here in brief: a coordinate-clicking agent never
generates the DOM-automation tells, so `navigator.webdriver` advice mostly
does not apply to it. What remains checkable is the engine fingerprint of the
machine the click lands in, the address it arrives from, and the
screenshot-think-click rhythm.
A CUA never triggers the DOM-automation flags sites check for, because its click is a
coordinate delivered through the input pipeline the same way a real click is, not a
script reaching into the page. Most bot-detection advice targets that automation layer
anyway: [`navigator.webdriver`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/webdriver),
leftover automation globals, DOM mutations that only a driver produces, an untrusted
event dispatched from code rather than from hardware. Those signals exist because a
selector-driven script reaches into the page and touches elements directly.
A CUA does not do that. It never calls `querySelector`, never sets an element's
value from script, never dispatches a synthetic event at a node it located by selector.
So the whole family of DOM-automation tells is [mostly not the thing that catches
it](navigator-webdriver-explained.md) - not because the agent hides them, but because
it never generates them in the first place.
That is the part people get wrong. They read that agents are hard to detect and assume
the fingerprint is solved. It is not solved. It is bypassed by the input method, and
two other surfaces are completely untouched by that fact.
## What stays checkable: the engine fingerprint
The agent clicks by coordinate, but the click still lands in a browser, and that
browser answers JavaScript. The site's own scripts still ask the engine what it is:
the WebGL renderer string, the canvas hash, the audio context, the installed fonts, the
screen geometry, the codec list. None of that goes through the DOM the agent avoids. It
goes through the ordinary JS surface every page can read, and a stock automation build
running on a server answers those questions like a server.
This is the surface invisible_playwright is built for. It is a Firefox patched at the
C++ level so the engine renders like a real Windows Firefox: the GPU strings, the
canvas and audio hashes, the font set and the screen all report values a real desktop
would report, derived from one seed so they stay consistent with each other. A
detector cross-checking those fields against one another finds agreement instead of the
contradictions a [half-patched or double-patched stack](playwright-stealth-levels.md)
produces.
The two-line launch is the same whether a human or a vision model drives it:
```python
from invisible_playwright import InvisiblePlaywright
# seed=42 makes the whole fingerprint reproducible run to run
with InvisiblePlaywright(seed=42) as browser:
page = browser.new_page()
page.goto("https://example.com")
# the screenshot -> click(x, y) -> screenshot loop a CUA runs
png = page.screenshot() # frame you hand to the vision model
x, y = 480, 320 # coordinate the model returns
page.mouse.click(x, y) # lands through the real input pipeline
png = page.screenshot() # next frame
```
`browser` here is a real Playwright
[`Browser`](https://playwright.dev/python/docs/api/class-browser), so
[`page.screenshot()`](https://playwright.dev/python/docs/api/class-page#page-screenshot)
and [`page.mouse.click()`](https://playwright.dev/python/docs/api/class-mouse#mouse-click)
are the ordinary documented methods - the same ones a coordinate-clicking agent already
calls. There is no special CUA API to adopt. You feed the screenshot to whatever model
you use and feed its coordinate back to `page.mouse.click`.
## What stays checkable: the action rhythm
The second surface the input method does not fix is timing, and it is the one specific
to agents.
A CUA's loop has a shape. Screenshot, then a pause while a model processes the image and
decides, then a click, then another screenshot. That thinking pause is roughly the same
length every step because it is model latency, not human hesitation, and it repeats with
a regularity no person produces. A human pause varies with what is on screen, drifts,
gets distracted, double-checks. A model's pause is a distribution centered on its
inference time.
invisible_playwright gives the pointer a Bezier-curve path between coordinates rather
than a teleport, which removes the crudest motion tell. It does not reshape the
step-to-step rhythm of your agent loop, because that rhythm is produced by your model
and your code, not by the browser. If your loop clicks every 1.9 seconds because that is
how long the model takes, the engine cannot know to vary it. You add the variance:
jitter the delay between steps, and do not click the instant a screenshot returns. This
is [the pause shaped like model latency](ai-agent-timing-signal.md), and it is
behaviour, which no fingerprint layer reaches.
## What invisible_playwright does not do
Being honest about the boundary is the point, because a coordinate agent makes it easy
to believe more is handled than actually is.
- **It does not change your IP.** The engine can look like a real Windows desktop and
still be sitting on a datacenter address that a site distrusts on sight. A perfect
fingerprint on a known-bad exit still loses. Bring a clean proxy; the engine cannot
supply one.
- **It does not fix per-account quotas or rate limits.** Those are counted server-side
against your account and address, and no browser property touches them.
- **It does not pace your agent.** The step rhythm above is yours to vary. The engine
handles the pointer path, not the schedule your loop runs on.
- **It does not see the DOM for you.** A CUA works by pixels precisely because it does
not read structure. invisible_playwright does not add DOM understanding; it makes the
browser those pixels are rendered in look real.
What it does do is remove the engine fingerprint from the list of things that give you
away, so that TLS, the driver layer and the render surface read as a genuine Firefox.
That is why it passes most fingerprint checks. It is not why a session with a bad IP and
a metronome rhythm passes, because it does not claim to fix those.
## A measurement worth trusting more than a verdict
The useful test for a CUA setup is not "did the suite say human". It is a field-by-field
comparison against a stock browser on the same machine, because the agent's own loop can
introduce timing the browser knows nothing about.
Open a fingerprinting page under invisible_playwright and under a stock Firefox on the
same host, and diff the reports. On the engine surface the two should agree: same GPU
family, a canvas hash that is stable across two reads in the same session (a hash that
changes per call is [a randomiser announcing itself](canvas-fingerprint-noise.md)), a
font list that belongs to the platform the user agent claims. Where they still differ,
after the address, is your candidate. A [software WebGL renderer or a
datacenter-shaped machine](playwright-docker-detection.md) survives every property patch
because it is not the engine's to change, and it is the most common reason a clean-looking
agent still gets a different page. Run it ten times, not once, because this domain is not
deterministic and a single green run is not a pass.
## Conclusion
Vision and coordinate agents move the detection problem, they do not remove it. The
DOM-automation flags that dominate ordinary Playwright advice are moot for them, because
a click delivered by pixel never generates those flags. What remains is the engine
fingerprint the site reads through its own JavaScript, and the machine-regular rhythm of
the screenshot-click loop. invisible_playwright answers the first: it makes the browser
render like a real Windows Firefox, seed-reproducible and self-consistent. The second is
yours - vary the timing - and so is the IP - bring a clean one. Handle all three and the
agent looks like a person on a real machine. Handle only the browser and you have a real
browser clicking like a robot.
## Short answers to the questions that lead here
**Do computer-use agents get detected as bots?** Not usually through `navigator.webdriver`
or DOM automation flags, because a coordinate click never produces them. They get caught
on the engine fingerprint, on the IP, or on the regular timing of the screenshot-click
loop.
**Does invisible_playwright work with OpenAI or Anthropic computer-use?** Yes. It returns
a real Playwright `Browser`, so `page.screenshot()` and `page.mouse.click(x, y)` - the
two calls a coordinate agent needs - work exactly as documented, on a Firefox that
renders like a real Windows desktop.
**If the agent clicks by pixel, is the fingerprint irrelevant?** No. The click method
avoids DOM tells, but the site still reads the engine through JavaScript. GPU, canvas,
audio, fonts and screen are all still checkable, and a stock server build answers them
like a server.
**Will it stop my agent being rate-limited?** No. Quotas and rate limits are counted
server-side against your account and address. No browser property changes them.
**How do I make the timing look human?** Jitter the delay between loop steps and do not
click the instant a screenshot returns. The engine varies the pointer path; the
step-to-step rhythm is produced by your model and your code, so you vary that.
**Does it fix my IP?** No. It makes the browser look real; it does not change the exit.
A real-looking browser on a datacenter address still loses, so bring a clean proxy.
## Sources
- OpenAI's own announcement, [Computer-Using Agent](https://openai.com/index/computer-using-agent/),
retrieved 2026-08-28, and Anthropic's own documentation, [Computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool),
retrieved 2026-08-28, both of which drive a browser through a screenshot to
coordinate-click to screenshot loop rather than by DOM selector.
- This project's own fingerprint gates and the stock-browser comparison method used to
separate an engine tell from a machine tell from a timing tell.
**See also:** [why AI agents have their own timing signal](ai-agent-timing-signal.md) for the
agent-specific timing tell in depth, [browser-use and what you can change](browser-use-detection.md)
for a selector-driven agent by contrast, and [why you can be blocked with a clean
fingerprint](why-blocked-with-a-clean-fingerprint.md) for the surfaces past the browser.
---
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
a Firefox patched at the C++ level driven by stock Playwright. The engine makes the
browser real; the pacing and the proxy are still yours to bring.*
The mechanism layer stays on this wiki:
[navigator.webdriver, explained](navigator-webdriver-explained.md),
[what a website can detect about a virtual machine](can-a-website-detect-a-virtual-machine.md),
and [the AI-agents integration pages](guides-ai-agents.md) for wiring a real
engine under a computer-use loop:
[back a computer-use agent with a real browser](back-computer-use-agent-real-browser.md).
@@ -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.
+4 -4
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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.
+3 -3
View File
@@ -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
+1 -1
View File
@@ -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
+6 -6
View File
@@ -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
+2 -2
View File
@@ -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
@@ -25,9 +25,10 @@ commonly over bad credentials or a destination it will not forward to.
`ERR_PROXY_CONNECTION_FAILED` fires earlier and more broadly: the browser never
managed to open a TCP socket to the proxy at all, whether the destination is HTTP or
HTTPS, whether authentication was ever going to be needed, before any `CONNECT`
exchange is possible. Chromium's own numbering reflects the ordering: `-130` for
`ERR_PROXY_CONNECTION_FAILED`, `-111` for `ERR_TUNNEL_CONNECTION_FAILED`, a
lower-level failure assigned a separate, earlier code on purpose.
exchange is possible. Chromium keeps them as two distinct codes for exactly
that reason: `-130` for `ERR_PROXY_CONNECTION_FAILED`, `-111` for
`ERR_TUNNEL_CONNECTION_FAILED` - one failure before any `CONNECT`, one during
it.
If you see `ERR_TUNNEL_CONNECTION_FAILED`, the proxy is reachable and rejected one
specific request. If you see `ERR_PROXY_CONNECTION_FAILED`, the proxy was never
@@ -145,7 +146,7 @@ fingerprint or engine-identity layer this project touches.
## Sources
- Chromium's [`net/base/net_error_list.h`](https://chromium.googlesource.com/chromium/src/+/main/net/base/net_error_list.h),
for the exact definitions of `ERR_PROXY_CONNECTION_FAILED` (-130) and the earlier,
for the exact definitions of `ERR_PROXY_CONNECTION_FAILED` (-130) and the
distinct `ERR_TUNNEL_CONNECTION_FAILED` (-111), retrieved 2026-08-30.
- [microsoft/playwright#9437](https://github.com/microsoft/playwright/issues/9437),
a real report of this exact error from a `server: "per-context"` proxy launch
+3 -3
View File
@@ -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
@@ -24,9 +24,10 @@ established` if the proxy agrees. Only then does the actual TLS handshake happen
inside that tunnel. `ERR_TUNNEL_CONNECTION_FAILED` fires when the CONNECT exchange
itself fails, before any TLS or HTTP traffic to the destination exists.
Chromium's own error list, which Firefox-under-Playwright inherits at the network-stack
naming level, defines it plainly: "a tunnel connection through the proxy could not be
established." The adjacent code, `ERR_PROXY_CONNECTION_FAILED`, is earlier and
Chromium's own error list defines it plainly: "a tunnel connection through the
proxy could not be established." (The name is Chromium's; Firefox's network
stack spells the same family of failures as `NS_ERROR_*` codes, and this page
uses the Chromium name because it is the one people search for.) The adjacent code, `ERR_PROXY_CONNECTION_FAILED`, is earlier and
different: it means the browser could not even open a TCP connection to the proxy
itself. `ERR_TUNNEL_CONNECTION_FAILED` means the browser did reach the proxy, and the
CONNECT for this specific destination is what failed. That distinction rules out "the
@@ -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
+2 -2
View File
@@ -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.*
+10 -4
View File
@@ -17,6 +17,12 @@ verified against the framework's actual source before anything is claimed about
several candidates that looked like a fit by star count turned out not to use
Playwright, or not to touch Firefox, at all.
These pages are for developers wiring an agent to this engine. The
agent-experience side - what to run, which agent products compare how, what to
check when an agent gets blocked - lives on the
[AIHawk wiki](https://github.com/feder-cr/AIHawk/wiki), the agent built on this
same engine.
## Framework integrations
- [Give a LangChain agent an invisible_playwright browser](langchain-agent-invisible-playwright-browser.md) - hand PlayWrightBrowserToolkit a launched browser so its tools inherit a real fingerprint.
@@ -28,15 +34,15 @@ Playwright, or not to touch Firefox, at all.
## Computer-use and screenshot agents
- [Back a computer-use agent with a real browser engine](back-computer-use-agent-real-browser.md) - implement the screenshot-and-click Computer interface over an invisible_playwright page, and its honest limits.
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable.
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. (Moved to the AIHawk wiki; the page here points across.)
- [DOM-reading vs screenshot agents: which stealth helps](dom-reading-vs-screenshot-agents.md) - which stealth signal helps depends on whether the agent reads DOM or clicks pixels.
## How AI agents get detected
- [AI browser agents and stealth: what fits and what does not](ai-browser-agents-stealth.md) - most agents drive Chromium over CDP, so a stealth Firefox does not drop in.
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach.
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes.
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop.
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach. (Moved to the AIHawk wiki; the page here points across.)
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes. (Moved to the AIHawk wiki; the page here points across.)
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop. (Moved to the AIHawk wiki; the page here points across.)
- [Playwright 1.62 Ships MCP In the Box](playwright-162-built-in-mcp.md) - the MCP server and a new playwright-cli are now bundled into core, runnable via `npx playwright mcp` with no separate install.
## Running agents at scale and on servers
+2
View File
@@ -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.
+2
View File
@@ -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.
+2
View File
@@ -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.
+24 -2
View File
@@ -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...
+4
View File
@@ -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.
+5 -5
View File
@@ -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 |
|---|---|---|---|
+2 -2
View File
@@ -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.
+1 -1
View File
@@ -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
+3 -3
View File
@@ -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
+4 -4
View File
@@ -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
@@ -193,6 +193,17 @@ responses mid-scrape](how-to-handle-403-429-backoff-mid-scrape-playwright.md).
```python
from datetime import timedelta
def read_row(row, week_start):
# the same shape as the first block, plus the week it came from
return {
"occurrence_id": row.get_attribute("data-occurrence-id"),
"class_name": row.locator(".class-name").inner_text(),
"instructor": row.locator(".instructor").inner_text(),
"room": row.locator(".room").inner_text(),
"start_time": row.get_attribute("data-start-iso"),
"week_start": week_start.isoformat(),
}
def pull_weeks(page, base_url, studio, start_week, max_weeks=8):
all_classes = []
for week_offset in range(max_weeks):
@@ -279,8 +290,8 @@ def scrape_schedule(studio, start_week, max_weeks=4):
with InvisiblePlaywright(seed=42) as browser:
page = browser.new_page()
capacities = {}
page.on("response", lambda r: on_response(r, capacities))
capacities.clear() # the module-level store the listener writes into
page.on("response", on_response)
rows = pull_weeks(page, "https://example.com/schedule",
studio, start_week, max_weeks)
@@ -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
@@ -118,11 +118,10 @@ a numbered or bulleted list under an "Inclusion Criteria" heading, another under
each line is not something a scraper should try to parse.
An age range written as "must be between 18 and 65 years of age" looks like two numbers
waiting to be extracted, until the next criterion reads "diagnosed within the last five
years" or "prior treatment with at least one but no more than three agents," where the
comparison, the units and the exceptions are all doing real work in the sentence. Storing
each criterion as its own string keeps the boundary honest: the scraper's job stops at
splitting the list, and a clinician or a downstream model reads the sentence.
waiting to be extracted, until the next criterion reads "prior treatment with at least one
but no more than three agents," where the comparison and the exception are doing real work
in the sentence. Storing each criterion as its own string keeps the boundary honest: the
scraper's job stops at splitting the list, and a clinician reads the sentence.
```python
def read_eligibility(page):
@@ -211,12 +210,11 @@ and gone through whatever review the registry requires before publishing it. A t
no results section is, more often than not, simply a trial whose results have not arrived
yet.
The distinction worth encoding is "not reported" versus "not applicable," and most
registries mark the second case explicitly rather than leaving it to be inferred: a note
attached to the results area stating that results reporting does not apply to this study
type or this outcome. Absent that explicit marker, treat a missing results section on a
completed or terminated trial as pending, not as evidence the study never finished, and
re-check it on the same schedule you use for status.
The distinction worth encoding is "not reported" versus "not applicable." Most registries
mark the second case explicitly, with a note attached to the results area stating that
reporting does not apply to this study type. Absent that marker, treat a missing results
section on a completed or terminated trial as pending, and re-check it on the same
schedule you use for status.
```python
def read_results_status(page):
@@ -238,13 +236,12 @@ a re-check cycle on a record that is already complete in every sense that matter
## Assembling one row per trial, sized for re-checking
Put the pieces together and the record for one trial is a dict with a handful of scalar
fields, two nested lists (eligibility, sites), and a checked-at timestamp that makes the
whole thing safe to overwrite on the next pass instead of trusting it forever. Getting to
that record usually means walking a paginated search listing first to collect trial URLs,
the same [numbered pagination](how-to-scrape-paginated-pages-playwright.md) pattern used
on any other listing page, then visiting each one, which is the general [list-to-detail
crawl](how-to-crawl-list-to-detail-pages-playwright.md) shape.
Put the pieces together and one trial's record is a dict with a handful of scalar fields,
two nested lists, and a checked-at timestamp that makes the whole thing safe to overwrite
on the next pass. Getting there means walking a paginated search listing first to collect
trial URLs, the same [numbered pagination](how-to-scrape-paginated-pages-playwright.md)
pattern used on any listing page, then visiting each one, the general
[list-to-detail crawl](how-to-crawl-list-to-detail-pages-playwright.md) shape.
```python
from invisible_playwright import InvisiblePlaywright
@@ -291,14 +288,13 @@ database](how-to-scrape-into-a-database-playwright.md), and it is what makes the
## Conclusion
A clinical trial listing is not one fact, it is several records at different ages sharing
a page. Status decays and needs a re-check timestamp. The registry-specific identifier and
the international identifier both belong on the row, because a dedup step across
registries needs the second one. Eligibility criteria stay as text, because the logic
inside them is not something a scraper should parse. Enrollment needs its label kept
alongside the number, or a target quietly becomes a headcount. Site status is a separate,
finer field than trial status. And a missing results section is usually a timing gap, not
a dead end, unless the page says otherwise. Build the row to be overwritten safely on the
next pass, and the pipeline stays honest about how current every field actually is.
a page. Status decays and needs a re-check timestamp. Both identifiers belong on the row,
because a dedup step across registries needs the international one. Eligibility criteria
stay as text, because the logic inside them is not something a scraper should parse.
Enrollment needs its label kept alongside the number, or a target quietly becomes a
headcount. Site status is a separate, finer field than trial status, and a missing results
section is usually a timing gap rather than a dead end. Build the row to be overwritten
safely on the next pass, and the pipeline stays honest about how current every field is.
## Short answers to the questions that lead here
@@ -315,21 +311,15 @@ inside the sentences is a separate problem from scraping the page.
often the target written into the protocol, and it is only an actual count when the page
labels it that way. Store the label with the number.
**A trial shows one status but a location page shows a different one for a specific
site. Which is right?** Both, because they are different fields. Trial-level status and
site-level status move independently, and a site can close or open without the overall
trial status changing.
**A trial shows one status but a listed site shows a different one. Which is right?**
Both. They are different fields, and a site can close or open without the overall trial
status changing.
**A completed trial has no results section. Is that a bug in my scraper?** Probably not.
Results are added long after registration, sometimes years later, so a completed trial can
legitimately show no results yet. Look for an explicit "not applicable" marker before
assuming the study never finished.
**How often should I re-scrape a trial once I have it?** Often enough that the
`status_checked_at` field stays meaningful for your use case. A recruiting trial changes
state more often than a completed one, so a fixed schedule for every trial wastes cycles
on the ones that rarely move and under-checks the ones that do.
## Sources
- Playwright's [`Locator`](https://playwright.dev/python/docs/api/class-locator) API,
@@ -339,10 +329,9 @@ on the ones that rarely move and under-checks the ones that do.
- Playwright's
[`wait_for_load_state`](https://playwright.dev/python/docs/api/class-page#page-wait-for-load-state),
used to detect the end of a pagination click before reading the next page's rows.
- This page describes registry mechanics in generic terms on purpose: field names,
status vocabularies and identifier formats differ between registries, so verify the
selectors above against the specific registry you are reading before trusting them
at scale.
- This page describes registry mechanics in generic terms on purpose, since field names
and identifier formats differ between registries: verify the selectors above against
the specific registry you are reading before trusting them at scale.
**See also:** [crawling a list to its detail pages](how-to-crawl-list-to-detail-pages-playwright.md)
for the general listing-to-detail shape used in the last section,
@@ -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 = {}
@@ -118,18 +118,28 @@ with zero sections and no error.
Click each course, wait for its own container rather than a timeout, then read:
```python
for course in page.query_selector_all("[data-course-id]"):
cid = course.get_attribute("data-course-id")
course.click()
page.wait_for_selector(f"[data-sections-for='{cid}'] [data-section-id]")
for sec in page.query_selector_all(f"[data-sections-for='{cid}'] [data-section-id]"):
rows.append(parse_section(sec, cid))
courses = page.locator("[data-course-id]")
ids = [courses.nth(i).get_attribute("data-course-id")
for i in range(courses.count())] # read ids first, hold no handles
for cid in ids:
page.locator(f"[data-course-id='{cid}']").click() # re-resolved every round
sections = page.locator(f"[data-sections-for='{cid}'] [data-section-id]")
sections.first.wait_for()
for i in range(sections.count()):
rows.append(parse_section(sections.nth(i), cid))
```
Waiting for the container keyed to that specific course matters. A generic wait on
`[data-section-id]` passes immediately because the previous course's sections are still
in the DOM, and you parse the same section twice under two different course codes.
Holding the element handles from a first pass and clicking them one by one looks
equivalent and is not. A catalog that re-renders its course list when a row expands
detaches every handle taken before that click, and the loop dies on the second course
with a detached-node error. Reading the identifiers first and re-resolving the locator on
each round costs one extra query and removes the failure.
The same trap in its general form is described in
[how to scrape a load-more button with Playwright](how-to-scrape-load-more-button-playwright.md).
@@ -207,28 +217,31 @@ that only the seat counts moved.
## Short answers to the questions that lead here
### Should one row be a course or a section?
A section. A course with two sections has two instructors, two schedules and two seat
**Should one row be a course or a section?** A section. A course with two sections has two instructors, two schedules and two seat
counts, and a course-level row cannot hold either pair without duplicating the other.
### Why do the seat numbers differ from the page?
The badge on the results page is usually a cached rendering that stops updating once a
**Why do the seat numbers differ from the page?** The badge on the results page is usually a cached rendering that stops updating once a
section closes. The section endpoint carries the current integers, so read the response
rather than the element.
### Why does the filtered result count not match the rows I extract?
Catalog filters commonly count courses while returning sections. Partition the crawl by
**Why does the filtered result count not match the rows I extract?** Catalog filters commonly count courses while returning sections. Partition the crawl by
department and term, then filter locally.
### Is a cross-listed course a duplicate?
No. It is one section reachable under two course codes. Keep one row per section and
**Is a cross-listed course a duplicate?** No. It is one section reachable under two course codes. Keep one row per section and
record the additional codes alongside it.
## Sources
- Playwright documentation, [Events and response handling](https://playwright.dev/python/docs/events), retrieved 2026-08-28
- Playwright documentation, [Auto-waiting](https://playwright.dev/python/docs/actionability), retrieved 2026-08-28
**See also:** [capturing XHR API responses](how-to-capture-xhr-api-responses-playwright.md)
for reading the section endpoint instead of the badge, [scraping a load-more button](how-to-scrape-load-more-button-playwright.md)
for the wait that passes on the previous panel, and [resuming an interrupted scrape](how-to-resume-an-interrupted-scrape-playwright.md)
for picking a long term back up.
---
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
a Firefox patched at the C++ level driven by stock Playwright. The generic wait on `[data-section-id]` is a mistake that shipped here first: it
passes on the previous course's sections and doubles them under a new code.*
@@ -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
@@ -194,9 +194,10 @@ changes rather than by how fast the machine can ask:
```python
import time
with sync_playwright() as p:
browser = p.firefox.launch()
page = browser.new_context().new_page()
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=7) as browser:
page = browser.new_page()
for postcode in POSTCODES:
set_postcode(page, postcode)
rows.extend(read_all_weeks(page))
@@ -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.
@@ -229,7 +229,7 @@ with InvisiblePlaywright(seed=42) as browser:
page.get_by_role("button", name="Get my quote").click()
results.append(caught.value.json())
page.close()
page.wait_for_timeout(rng.randint(4000, 11000))
time.sleep(rng.randint(4, 11)) # the page is closed; pause off it
```
The pause between profiles is doing the same job the pause between clicks does
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more