Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31969d5e3b | ||
|
|
b6d24ebbbf | ||
|
|
1c4d8859ae | ||
|
|
b09d23c05b | ||
|
|
97bf5ddf94 | ||
|
|
c6c38ab327 | ||
|
|
a00b421298 | ||
|
|
ab5f6a98b0 | ||
|
|
1a46abb6b8 | ||
|
|
e28658a75a | ||
|
|
b7af7a0f02 | ||
|
|
f43f0a60a6 | ||
|
|
720cbf4799 | ||
|
|
ddb7058f2b | ||
|
|
1fae640048 | ||
|
|
080b6ffdaa | ||
|
|
9833d053fa | ||
|
|
84146233e4 | ||
|
|
174ceebc89 | ||
|
|
5ec3ca3f6e | ||
|
|
accc852849 | ||
|
|
c6d423db7e | ||
|
|
0f73547619 | ||
|
|
fa1533eb70 | ||
|
|
8ade6f90ad | ||
|
|
0c061e6410 | ||
|
|
67bfe5beea | ||
|
|
296fb10b57 | ||
|
|
39fcd4cdb6 | ||
|
|
8ebc075d49 | ||
|
|
c419762864 | ||
|
|
5521fee86c | ||
|
|
ed2259a405 | ||
|
|
a0e04af8e6 | ||
|
|
57ef9cd523 | ||
|
|
971ecb945f | ||
|
|
c2f1764fc4 | ||
|
|
ecbf313a05 | ||
|
|
1c0bf446ce | ||
|
|
89563a2dd7 | ||
|
|
07efe3944c | ||
|
|
f2b648f7cf | ||
|
|
ff096b4d1b | ||
|
|
84192938cb | ||
|
|
53b7996bc3 | ||
|
|
7567dbc52b |
No files matched your search
@@ -7,6 +7,23 @@
|
||||
# links to the wiki's extensionless form, names each page by its slug (index.md
|
||||
# becomes Home.md), and regenerates _Sidebar.md from the parent/nav_order tree.
|
||||
#
|
||||
# ⛔ THE RELEASE TRIGGER DOES NOT FIRE FOR THE RELEASES THIS REPOSITORY MAKES.
|
||||
# GitHub does not start a workflow from an event created with the built-in
|
||||
# GITHUB_TOKEN, and publish.yml creates the release - which is why every recent
|
||||
# release here is authored by github-actions[bot]. Measured 2026-09-15 across
|
||||
# 43 runs: all but a couple were manual dispatches, and the two `release` events
|
||||
# are old enough to predate the automation. The sibling package AIHawk had the
|
||||
# identical defect and the identical false sentence in this comment.
|
||||
#
|
||||
# The cost is the same too: since the last dispatch on 2026-09-14 the docs have
|
||||
# moved by 37 insertions and 15 deletions with a release in between, and the
|
||||
# published wiki was showing neither.
|
||||
#
|
||||
# So it also runs on a PUSH to main that touches what the wiki is made of - the
|
||||
# pages, the converter, and this file - which is an event that actually happens
|
||||
# here. The release trigger stays: it costs nothing and works for a release a
|
||||
# person publishes. It is simply no longer what this depends on.
|
||||
#
|
||||
# It runs on a published release (the docs the release ships are what the wiki
|
||||
# should show) and on manual dispatch. The wiki checkout is wiped and rebuilt
|
||||
# each run so a page deleted from docs/ also disappears from the wiki; nothing
|
||||
@@ -20,6 +37,13 @@
|
||||
name: publish-wiki
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "docs/**"
|
||||
- "scripts/build_wiki.py"
|
||||
- "scripts/sync_article_pixels.py"
|
||||
- ".github/workflows/publish-wiki.yml"
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch: {}
|
||||
@@ -44,7 +68,25 @@ jobs:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Render docs/ into a wiki build directory
|
||||
run: python scripts/build_wiki.py docs wiki_build
|
||||
run: python scripts/build_wiki.py docs wiki_build --pixels "${{ github.repository }}"
|
||||
|
||||
# The view counters. Upload BEFORE the push, never after: a page that
|
||||
# reaches the wiki without its asset serves a 404 for its own pixel and
|
||||
# counts nothing until the next release. Uploading only what is missing
|
||||
# makes this a no-op on a run that adds no pages.
|
||||
- name: Give every new page its view pixel
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: python scripts/sync_article_pixels.py --repo "${{ github.repository }}" wiki_build
|
||||
|
||||
# And the gate. `build_wiki.py` writes no pixel when it is not told which
|
||||
# repository it is building for, which is the right default for a local
|
||||
# preview and a silent disaster here: the wiki would publish, look
|
||||
# perfectly normal, and count nothing. This is the step that notices.
|
||||
- name: Check every page carries its own pixel
|
||||
run: |
|
||||
python scripts/sync_article_pixels.py --selftest
|
||||
python scripts/sync_article_pixels.py --repo "${{ github.repository }}" --check wiki_build
|
||||
|
||||
- name: Publish to the wiki
|
||||
env:
|
||||
|
||||
@@ -213,6 +213,18 @@ jobs:
|
||||
git config user.name "feder-cr"
|
||||
git config user.email "85809106+feder-cr@users.noreply.github.com"
|
||||
git add PUBLISHED.json
|
||||
# `record` also realigns this version's CHANGELOG heading to the upload
|
||||
# date the index reports, and this is the repository that keeps a
|
||||
# changelog, so this is where it matters. A file rewritten on the
|
||||
# runner's disk that nobody stages is a change that never happened, and
|
||||
# the whole point is that the date stops being written by hand: 0.16.2
|
||||
# shipped dated a day ahead because the heading is typed at bump time,
|
||||
# hours before the upload it claims to describe, in whatever timezone
|
||||
# the author is in. Conditional to match the release notes step below,
|
||||
# and because `git add` on a missing path fails under `bash -e`.
|
||||
if [ -f CHANGELOG.md ]; then
|
||||
git add CHANGELOG.md
|
||||
fi
|
||||
git commit -m "record $VERSION as published"
|
||||
BRANCH="${{ github.event.repository.default_branch }}"
|
||||
if git push origin "HEAD:refs/heads/$BRANCH"; then
|
||||
|
||||
@@ -35,19 +35,30 @@ jobs:
|
||||
# being made.
|
||||
english:
|
||||
name: the repository is English
|
||||
# ⛔ The gate is `invisible_core.english` since core 30.23.0, not a script of
|
||||
# this repository: the script was a COPY, one here and one in AIHawk, and the
|
||||
# copies drifted - this one never gained the `.js/.css/.html` coverage the
|
||||
# other did. So this job needs the pinned core on the index, like `unit`.
|
||||
needs: core-on-index
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: install the pinned core, which carries the gate
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e .
|
||||
- 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.
|
||||
# edit to its word list. What this repository exempts is declared in
|
||||
# `[tool.invisible.english]` in pyproject.toml, and an exclusion that
|
||||
# names nothing is refused.
|
||||
run: |
|
||||
python scripts/check_english_only.py --selftest
|
||||
python scripts/check_english_only.py
|
||||
python -m invisible_core.english --selftest
|
||||
python -m invisible_core.english
|
||||
|
||||
# `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
|
||||
@@ -211,8 +222,25 @@ jobs:
|
||||
python scripts/check_docs_api_surface.py --selftest
|
||||
python scripts/check_docs_api_surface.py
|
||||
|
||||
# `gate` is the ONLY context main requires, so a check this job does not wait
|
||||
# for is a check the branch protection cannot see. It waited for three of the
|
||||
# five, and the two it left out are not minor ones: `english` is the gate
|
||||
# written FOR this repository after 549 lines of Italian shipped here in one
|
||||
# subsystem, and `version` is what stands between a forgotten bump and a
|
||||
# release that publishes nothing and reports success. Either could go red
|
||||
# while this job went green and the push landed on main regardless - which is
|
||||
# the decorative protection this project has already met once, on the branch
|
||||
# rules that required job names no job produced any more.
|
||||
#
|
||||
# `skipped` is not a failure and must not be treated as one: `version` runs on
|
||||
# pull requests only and is skipped on every push to main, and `unit` and
|
||||
# `docs-api` are skipped during the window when the pinned core is not on the
|
||||
# index yet. The case arms name failure and cancelled, so a skip passes on
|
||||
# purpose. That is also why each arm carries its own sentence: a gate that
|
||||
# exits 1 without saying which of five inputs went red is a gate somebody has
|
||||
# to open five tabs to read.
|
||||
gate:
|
||||
needs: [core-on-index, unit, docs-api]
|
||||
needs: [core-on-index, unit, docs-api, english, version]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -221,6 +249,8 @@ jobs:
|
||||
echo "core-on-index: ${{ needs.core-on-index.result }}"
|
||||
echo "unit: ${{ needs.unit.result }}"
|
||||
echo "docs-api: ${{ needs.docs-api.result }}"
|
||||
echo "english: ${{ needs.english.result }}"
|
||||
echo "version: ${{ needs.version.result }}"
|
||||
case "${{ needs.unit.result }}" in
|
||||
failure|cancelled) echo "the suite did not pass"; exit 1 ;;
|
||||
esac
|
||||
@@ -230,6 +260,12 @@ jobs:
|
||||
case "${{ needs.docs-api.result }}" in
|
||||
failure|cancelled) echo "the guides name something that does not exist"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.english.result }}" in
|
||||
failure|cancelled) echo "the repository is not English"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.version.result }}" in
|
||||
failure|cancelled) echo "the version this change proposes is already taken"; exit 1 ;;
|
||||
esac
|
||||
echo "ok"
|
||||
|
||||
# Measured 2026-09-04: 0.10.0 was on the index while main sat on 0.10.0 with
|
||||
|
||||
@@ -6,6 +6,371 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.22.0] - 2026-09-17
|
||||
|
||||
### Fixed
|
||||
- **`strict` now refuses an ambiguous selector instead of picking one.** The
|
||||
option was accepted across the public API, the injected script has always
|
||||
known how to raise on it, and nothing in between passed it on: the default
|
||||
stayed false all the way down. Every Locator method sends `strict=True`, so
|
||||
`page.locator("button").click()` on a page with two buttons clicked the
|
||||
FIRST one and reported success. That is not a missing error message. The
|
||||
automation acted on an element nobody had chosen, and said nothing about it.
|
||||
- **`force` now bypasses the actionability checks it promises to bypass**, and
|
||||
both of them: the state checks and the hit-target check. "Receives events"
|
||||
is one of the checks the option names, and an overlay intercepting the
|
||||
pointer is the ordinary reason to pass it, so honouring only the first half
|
||||
would leave the option indistinguishable from doing nothing.
|
||||
|
||||
### Changed
|
||||
- The server reads the per-action options in ONE place rather than one reader
|
||||
per option. A reader per option is the shape that lost these two: seven
|
||||
copies of `params.get("trial")` is how the eighth action gets written
|
||||
without one. A test derives the list of actions that can carry the options
|
||||
from the code and requires every operation reaching one of them to hand
|
||||
them over, so an action added without the wiring is red on the day it is
|
||||
written.
|
||||
- `no_wait_after` is NOT in this list, and the note that grouped it with the
|
||||
other two was wrong. Upstream declares it deprecated and without effect, so
|
||||
a client that ignores it matches upstream rather than departing from it.
|
||||
|
||||
## [0.21.0] - 2026-09-17
|
||||
|
||||
### Added
|
||||
- **`go_back()` and `go_forward()` are back**, and the cause 0.18.0 withdrew
|
||||
them for turned out to be here rather than in the engine. A restored
|
||||
document left this client holding the injected script it had cached PER
|
||||
FRAME, while that script is an object inside one execution CONTEXT, and a
|
||||
frame outlives its contexts: every navigation replaces them and so does a
|
||||
restore. The handle and the context it was minted in are stored together
|
||||
now, so "is this still mine" is decided from state rather than inferred
|
||||
from destruction events arriving complete and in order. They do not: on a
|
||||
restore the engine destroys worlds this client was never told existed.
|
||||
- The end to end test walks back, forward and back again and READS THROUGH A
|
||||
LOCATOR each time. One movement was green against the defect, and so is
|
||||
asserting on the URL: both of the earlier tests did one of those.
|
||||
|
||||
### Changed
|
||||
- The perimeter's `WITHDRAWN` set is empty again and stays declared, for the
|
||||
next operation that is written and cannot be trusted yet.
|
||||
|
||||
## [0.20.0] - 2026-09-16
|
||||
|
||||
### Added
|
||||
- **A gate on what the injected script leaves on the page's NODES.** The half of
|
||||
this class that concerned the page's `window` was closed in 0.19.0; this is
|
||||
the other verb. `computeAriaRef` writes `element._ariaRef` while building the
|
||||
accessibility tree, reachable only through `mode="ai"`, and the question
|
||||
underneath had never been answered: does an assignment made through an Xray
|
||||
stay in the sandbox, or reach the page's node?
|
||||
|
||||
Measured against a page served from `127.0.0.1` that watches its own elements:
|
||||
it stays. With `mode="ai"` the snapshot comes back carrying refs and the
|
||||
sandbox sees the expando, while the page sees nothing at all. Nothing was
|
||||
broken and nothing needed fixing - but the day that confinement stops holding,
|
||||
every interactable element would carry a property any page can enumerate, and
|
||||
nothing would have said so. The test drives the writing branch deliberately
|
||||
and fails if it ever stops being reached, so it cannot go quietly green.
|
||||
|
||||
## [0.19.0] - 2026-09-16
|
||||
|
||||
### Changed
|
||||
- **A click has a duration now, and a double click has an interval.**
|
||||
`mousedown` and `mouseup` used to leave together, so what a page measured as
|
||||
the hold was **8.0 ms** against the 60-120 ms a finger takes; and the two
|
||||
presses of a double click had nothing between them, yet were still delivered
|
||||
as a `dblclick`, because that event is born from `clickCount` rather than from
|
||||
the interval - so a page received a double click no operating system would
|
||||
have accepted as one. Both now come from the session's `PointerPersona`, and
|
||||
`delay=`, which was dropped here along with `button` and `modifiers` before
|
||||
it, works again as the override Playwright documents it to be.
|
||||
`humanize=False` keeps the old behaviour.
|
||||
|
||||
- **Typing now takes the time a hand takes, and that is a real slowdown you
|
||||
should know about before upgrading.** `page.type`, `locator.press_sequentially`,
|
||||
`keyboard.type` and the typing half of `fill` used to emit keys as fast as the
|
||||
protocol allows: a `keydown` and its `keyup` measured **4.0 ms** apart on a
|
||||
real page, against the 60-120 ms a finger takes, and eleven characters went by
|
||||
in about 50 ms. A site does not have to probe for that, it only has to listen,
|
||||
and a password field is where that listening is already installed. The rhythm
|
||||
now comes from a `TypingPersona` drawn from the session seed - dwell, gaps,
|
||||
the digram structure that makes alternating hands faster than one hand, and
|
||||
occasional hesitations - so `password123` takes about 1.8 s instead of 50 ms.
|
||||
Same seed still types the same way. `humanize=False` keeps the old speed, and
|
||||
the `delay=` you pass still wins over the persona for that call.
|
||||
|
||||
- **A drag travels now, instead of arriving.** The whole of `drag_and_drop` was
|
||||
five events, and the two carrying the journey were identical and 7 ms apart -
|
||||
a pair no device can report, since a move event is born from moving. They were
|
||||
deliberate: one jump alone did not reliably start the drag. Measured on a
|
||||
480-pixel drag, that journey now takes 27 events over 26 distinct points, on a
|
||||
path drawn by the same generator and delivered under the same pacing rules as
|
||||
every other pointer movement this package makes. The approach to the source is
|
||||
a path too. `humanize=False` keeps a single event, and `humanize=<seconds>`
|
||||
now caps this movement as it already capped every other one.
|
||||
|
||||
### Fixed
|
||||
- **`drag_and_drop` raised on a `draggable` element, and left the mouse button
|
||||
down.** Gecko started a native drag session off that single 480-pixel jump,
|
||||
`dispatchDragEvent` then failed with `NS_ERROR_FAILURE`, and the `mouseup`
|
||||
never went out - so the `buttons` field of every event after it said
|
||||
"pressed", including the recovery `mouseup` in the error path, which failed
|
||||
the same way. The whole of HTML5 drag and drop was therefore unusable and
|
||||
nothing said so, because there was no end-to-end test of a drag at all. With a
|
||||
real path the drag is born the way it is for a hand and the gesture completes.
|
||||
It is the same change as the entry above: one absence, three symptoms.
|
||||
- **`delay=` on typing was measured in milliseconds and slept in seconds.** The
|
||||
public API documents it in milliseconds; the one server path that forwarded it
|
||||
handed the number straight to `time.sleep`, so
|
||||
`element_handle.type("abc", delay=100)` waited five minutes instead of 0.3
|
||||
seconds. The six paths that dropped the value were accidentally protected from
|
||||
the bug the seventh had. All seven honour it now, and the unit is in the name.
|
||||
- **`trial=True` no longer performs the action.** It is accepted on 31 public
|
||||
signatures - click, dblclick, hover, tap, check, uncheck, set_checked and drag
|
||||
across `Page`, `Frame`, `Locator` and `ElementHandle` - and the word appeared
|
||||
nowhere in the engine client, so it reached the wire and fell off it: a call
|
||||
whose whole purpose was not to click clicked. The single place that did read it
|
||||
made the outcome worse rather than better, skipping the humanised pointer
|
||||
approach and then running the action anyway, so the click went out in the most
|
||||
recognisable shape a click has. It is honoured now in the retry loop, which is
|
||||
the only thing that knows what actionable means: the checks run, the hit target
|
||||
is verified, and nothing is dispatched. A drag checks both ends.
|
||||
|
||||
- **A mis-aimed click is retried instead of blocked, and the injected script
|
||||
no longer touches the page's window at all.** The hit-target interceptor
|
||||
installed capture listeners there for the duration of every action and
|
||||
called `preventDefault` on the events that landed on the wrong element.
|
||||
Both halves are gone. The listeners were the last thing this package left
|
||||
on the page, and the blocking was the worse half: a real `mousedown` that
|
||||
disappears is not something an input stack produces, so the defence
|
||||
announced itself exactly when it worked. The check is now a pure DOM read
|
||||
run before the action and again after it, so a target that moves is caught
|
||||
and the action retried. What a page sees is a click that landed where the
|
||||
thing it was aimed at used to be, which is what a hand produces when a
|
||||
layout shifts. The guarantee narrows in one case: an element that moves
|
||||
between the check and the event now receives that one event before the
|
||||
retry, where before it received none.
|
||||
## [0.18.0] - 2026-09-16
|
||||
|
||||
### Removed
|
||||
- **`go_back()` and `go_forward()` now refuse.** 0.17.0 made them work for one
|
||||
step, and one step is the problem. The engine restores the document and
|
||||
reports the navigation, but a restored page leaves the driver holding a stale
|
||||
handle for that page's world: go forward, or go back a second time, and every
|
||||
locator raises `Cannot find object with id` while `evaluate()` and
|
||||
`content()` keep answering from the right document. `reload()` clears it.
|
||||
A method that is right once and wrong afterwards puts the failure somewhere
|
||||
else, where it reads as a broken selector on a healthy page, so both refuse
|
||||
with a sentence naming what would have happened. Navigate to the URL instead;
|
||||
`reload()` is unaffected, and a page moving its own history with
|
||||
`history.back()` still restores from the cache.
|
||||
|
||||
### Changed
|
||||
- The perimeter gained a fifth category, `WITHDRAWN`, for an operation that is
|
||||
written and held back by a defect rather than missing. The four that existed
|
||||
would each have said something untrue about these two, and an inventory that
|
||||
lies is worse than one with a gap.
|
||||
- The README stops claiming all methods. It never covered tracing, HAR, CDP or
|
||||
the API request context, and every refusal has said so for a while; the
|
||||
headline had not caught up.
|
||||
## [0.17.0] - 2026-09-16
|
||||
|
||||
### Fixed
|
||||
- **An authenticated HTTP or HTTPS proxy routes the page again.** It was
|
||||
accepted and then bypassed, silently, on every engine from firefox-24 to
|
||||
firefox-30: the credentials went to the proxy endpoint, where Gecko
|
||||
implements them for SOCKS only, so the call failed inside the channel filter
|
||||
and the connection went out directly over the host's own address with
|
||||
nothing raised anywhere. SOCKS was unaffected, which is why it lived through
|
||||
seven releases. HTTP proxy auth answers the 407 challenge instead, and that
|
||||
path was already wired. Reported from the outside, not caught here. There is
|
||||
now an end to end test that drives a browser through an authenticated HTTP
|
||||
proxy, on both the launch road and the context road, which is the case
|
||||
nothing covered.
|
||||
- **`go_back()` and `go_forward()` report the navigation they performed.** The
|
||||
engine went back all along; Juggler had no bookkeeping for a document
|
||||
restored from the back forward cache, so the client was never told the
|
||||
navigation had committed. The test asserts that going back RESTORES the
|
||||
document rather than fetching it again, because asserting on the URL alone
|
||||
passes against a browser that silently refetches.
|
||||
|
||||
### Changed
|
||||
- Pinned engine moves to **firefox-31**, via `invisible-core` 31.23.0.
|
||||
- The pinning page's worked examples now run as written. Two of them named a
|
||||
GPU the validated pool cannot present and raised when copied.
|
||||
- The ledger step realigns this file's heading date to the date the index
|
||||
reports, so a heading typed hours before the upload it describes cannot
|
||||
disagree with the gate that checks it.
|
||||
## [0.16.2] - 2026-09-15
|
||||
|
||||
### Changed
|
||||
- **The language gate comes from the core.** The check that this repository
|
||||
is English used to be a script here and a copy in AIHawk, and the copies
|
||||
drifted: this one never gained the `.js`, `.css` and `.html` coverage the
|
||||
other did, so the front end was outside its sight. It now runs as
|
||||
`invisible_core.english` from the pinned core, `invisible-core` 30.23.0,
|
||||
and what this repository exempts is declared once in
|
||||
`[tool.invisible.english]` in `pyproject.toml`. An exclusion that names
|
||||
nothing is refused, which is the check the copies did not have.
|
||||
- **Three names cross into English with the core.** `srflx_to_declare()`,
|
||||
the `srflx_declared` keyword of `build_launch_env` and the attribute that
|
||||
carries the decision follow the core's rename in the same release, because
|
||||
either half alone breaks the launch. Nothing the browser receives changes:
|
||||
the emitted prefs and the launch environment are byte-identical to 0.16.1.
|
||||
|
||||
## [0.16.1] - 2026-09-15
|
||||
|
||||
### Fixed
|
||||
- **Setting real files on a file input works.** Both doors ended in
|
||||
`InvalidStateError: An attempt was made to use an object that is not, or is
|
||||
no longer, usable`, a sentence naming no file, no API and no preference. The
|
||||
refusal is in the parent process: it declines to build a `File` for any
|
||||
content process whose remote type is not `file`. The preference the engine's
|
||||
own gate calls the "or for testing" escape ships from `invisible-core`
|
||||
30.22.0, which this release pins, and the two tests that covered the defect
|
||||
are hard assertions again for the first time since it was opened.
|
||||
- **`FileChooser.set_files()` could not upload anything, and said so.** A
|
||||
chooser already holds the input element, so the client asks the
|
||||
`ElementHandle` for `setInputFiles` rather than going through a selector, and
|
||||
this package had no such method: the whole listening half of the file-chooser
|
||||
feature led to a dispatcher that correctly reported a gap rather than a
|
||||
decision. The element handle now performs the same upload the frame does,
|
||||
through the same action and the same reader of the request, so there is one
|
||||
upload path and not two. The engine-side half of file uploads is a preference
|
||||
that belongs to `invisible-core` and arrives when the pin moves: the two
|
||||
tests covering it stay expected-red until then, and are now strict so they
|
||||
turn red the day they start passing.
|
||||
- **`locator.scroll_into_view_if_needed()` works. It never had.** It sent the
|
||||
engine command `Page.scrollIntoViewIfNeeded`, whose handler calls
|
||||
`scrollRectIntoViewIfNeeded` - a method declared in no binding of `Element`
|
||||
anywhere in the engine, so it was `undefined` for every caller and the call
|
||||
threw every time. Measured at four positions, including an element already in
|
||||
view: a timeout on all four, while `bounding_box()` on the same element
|
||||
answered correctly. The package already knew how to scroll, in the one place
|
||||
that mattered: every click has scrolled through the injected script since a
|
||||
click below the fold was found to miss. The public method now calls that same
|
||||
helper, so there is one scroll and not two. It centres the element rather than
|
||||
scrolling the minimum, and a `rect` argument is not honoured.
|
||||
|
||||
### Added
|
||||
- **Every operation that refuses now says so in `_juggler/perimeter.py`, and a
|
||||
test keeps it that way.** Ten operations raised `ProtocolException` inline
|
||||
with a good reason beside the code and nothing anywhere that recorded they
|
||||
existed, so there was no way to tell a deliberate refusal from a gap without
|
||||
reading the dispatcher end to end. They are declared in three sets that keep
|
||||
the distinction: the engine offers no command (`drop`, `setOffline`,
|
||||
`setWebSocketInterceptionPatterns`), the answer is fixed when the injected
|
||||
script is built (`registerSelectorEngine`, `setTestIdAttributeName`), or it is
|
||||
simply not written yet (`exposeBinding`, `frameElement`, `resolve`, `reject`,
|
||||
`setExtraHTTPHeaders`). The test fails both ways: a new inline refusal nobody
|
||||
declares, and a declared name that has since started working.
|
||||
|
||||
## [0.16.0] - 2026-09-15
|
||||
|
||||
### Changed
|
||||
- **A GPU pin now selects a validated persona instead of setting a label, and an
|
||||
impossible value is refused rather than ignored.** `pin={"gpu.renderer": ...}`
|
||||
used to change the `Profile` object and leave the browser reporting the seed's
|
||||
own GPU: measured on seed 1561645783, the profile said AMD RX 7900 XTX while
|
||||
`zoom.stealth.webgl.renderer` stayed the seed's NVIDIA GTX 980. The same held
|
||||
for `gpu.vendor` and `gpu.class_tier`, so all three keys were decorative with
|
||||
respect to the page. A renderer string cannot travel alone - around 81
|
||||
`getParameter` values, the shader precisions and the extension list belong to
|
||||
the same GPU - so a pin picks one of the validated personas, and a renderer,
|
||||
vendor or class the pool cannot present raises with the available values named.
|
||||
Sessions that pin nothing are unaffected: 404 seeds emit byte-identical
|
||||
preferences before and after.
|
||||
- **`webgl.msaa_samples` is no longer a pin key.** The engine now emits the same
|
||||
MSAA sample count on Windows and Linux, so a pin has nothing left to move.
|
||||
Before this, the value was honoured on Linux and held at 4 on Windows, and the
|
||||
two builds emitted a different `gl.SAMPLES` for the same seed on seven of eight
|
||||
measured seeds.
|
||||
|
||||
### Fixed
|
||||
- **`docs/pinning.md` described behaviour the code did not have.** It said
|
||||
`gpu.renderer` "lands verbatim in `UNMASKED_RENDERER_WEBGL`" and "does not
|
||||
condition other fields"; both were the opposite of true. The README example
|
||||
pinned a card no validated persona carries, so the snippet a reader copied did
|
||||
nothing.
|
||||
|
||||
- **The pinning surface loses three keys that could not work.** `screen.tier`
|
||||
could not condition the screen it named, because pins are applied after the
|
||||
sampler has drawn. `screen.avail_width` and `screen.avail_height` were
|
||||
page-contradicting: the engine derives the available rect from `width`,
|
||||
`height` and `taskbar_px`, so pinning either moved a label on the profile and
|
||||
nothing a page reads. Pin `screen.width`, `screen.height` and
|
||||
`screen.taskbar_px`; the available rect follows from them.
|
||||
- **`codec.webspeech_synth` is gone from the profile.**
|
||||
`media.webspeech.synth.enabled` is emitted as a constant `true`, which is what
|
||||
retail Firefox does on desktop, so the sampled field only ever made the profile
|
||||
disagree with the browser - on about 12% of seeds.
|
||||
|
||||
### Internal
|
||||
- Requires `invisible-core==30.21.0`.
|
||||
- `_cursor.humanize_prefs` is deleted. It was a second implementation of the
|
||||
`stealthfox.humanize*` contract with no caller in `src/`, and it disagreed with
|
||||
the live one: it never emitted `stealthfox.humanize.stepMs`. The two properties
|
||||
its tests asserted now run through `_session.build_prefs`, which is the
|
||||
function both front doors actually call.
|
||||
|
||||
## [0.15.2] - 2026-09-14
|
||||
|
||||
### Fixed
|
||||
- **`evaluate` no longer rewrites the JavaScript you passed it.** The argument
|
||||
was placed by searching the built script for the placeholder `ARG` and
|
||||
replacing it - over a string that already held your expression - so those
|
||||
three uppercase letters were rewritten to the argument's JSON anywhere they
|
||||
appeared in your own code. `'CARGO'.length` answered 6 instead of 5, a
|
||||
selector `[data-role='TARGET']` matched nothing, `/ARGH/` became `/nullH/`,
|
||||
and `const ARG = 5` was a syntax error. The three letters only had to appear
|
||||
inside a longer word, and three of those four failures were silent. The
|
||||
argument is now placed in the same formatting pass that inserts the
|
||||
expression, so your code is never scanned. `page.evaluate`,
|
||||
`page.evaluate_handle` and `page.wait_for_function` were affected;
|
||||
`element_handle.evaluate` and `eval_on_selector` already built their wrapper
|
||||
this way and were not.
|
||||
- The script the page actually runs is unchanged, character for character, for
|
||||
every expression that did not spell the placeholder, and a test pins it:
|
||||
`evaluate` is the one call that deliberately runs in the main world, so the
|
||||
shape of that wrapper is something a site can look at.
|
||||
|
||||
## [0.15.1] - 2026-09-14
|
||||
|
||||
### Changed
|
||||
- **The engine is `firefox-30`, through `invisible-core 30.19.0`.** The
|
||||
screencast capture no longer ends for good when a headed window is
|
||||
minimised for a moment: the engine listens for its capture module ending,
|
||||
starts another one a second later for as long as the window cannot be
|
||||
captured, and repeats the last frame every 250 ms while the module is
|
||||
quiet, so the age of a frame means one thing to a client that watches it.
|
||||
Nothing else moves: the pin follows the seal.
|
||||
|
||||
## [0.15.0] - 2026-09-14
|
||||
|
||||
### Changed
|
||||
- **A closed pipe is a closed target.** A call made after the browser's pipe
|
||||
closed, or one that was waiting when it closed, now raises
|
||||
`TargetClosedError` - the same class a call on a disposed page, context or
|
||||
browser raises - instead of a plain `Error` carrying `the pipe closed`. The
|
||||
browser being gone is one fact and reaches a caller as one type.
|
||||
- `invisible_playwright.async_api` and `invisible_playwright.sync_api` export
|
||||
`Error`, `TimeoutError` and `TargetClosedError`, so a caller can catch the
|
||||
type without importing a private path.
|
||||
|
||||
## [0.14.0] - 2026-09-08
|
||||
|
||||
### Added
|
||||
- **`page.screencast.start(fps=...)` sets the frame rate, and the default
|
||||
stays at ten.** The engine has taken a frame rate all along, and the wrapper
|
||||
passed its own constant to it whatever the caller asked, so a live view could
|
||||
not go past ten frames a second no matter what it did. Measured on the same
|
||||
page, interleaved arms: asking for 10 delivers 9.6-9.8 fps at 257 KB/s,
|
||||
asking for 25 delivers 23.8-24.0 at 629 KB/s. The default does not move,
|
||||
which is the whole shape of the change: raising it would put two and a half
|
||||
times the bandwidth on every consumer to serve the one that is watching a
|
||||
window, so the caller decides and the constant is what happens when nobody
|
||||
does. That is how `quality` and `size` on the same call already work.
|
||||
|
||||
## [0.13.2] - 2026-09-07
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -23,21 +23,6 @@ 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).
|
||||
|
||||
---
|
||||
|
||||
## Still seeing captchas or anti-bot? It's the proxy.
|
||||
Once the browser is handled it stops being the variable. If you are still getting challenged, the tell is no longer the browser, it is the IP you come from. Around 90% of proxies are public: anyone can rent the same address, so it is already known and sits on the blocked-IP lists sites check. A perfect browser on a known IP still loses.
|
||||
|
||||
---
|
||||
|
||||
## Install
|
||||
@@ -49,27 +34,13 @@ python -m invisible_playwright fetch # one-time download, sha256-verified:
|
||||
|
||||
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.
|
||||
Supported platforms: **Windows x86_64**, **Linux x86_64 / arm64**.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
### Random fingerprint per session
|
||||
**100% Playwright-compatible** - sync and async, all methods, zero API changes. If you already use Playwright, switching is two lines:
|
||||
**Playwright's API, sync and async, with no code changes.** The same objects, the same calls, the same return values. A few surfaces are out of scope - tracing, HAR, CDP, the API request context - and each one refuses with a sentence saying why rather than misbehaving quietly. If you already use Playwright, switching is two lines:
|
||||
|
||||
```diff
|
||||
- from playwright.sync_api import sync_playwright
|
||||
@@ -156,8 +127,8 @@ By default everything comes from `seed`. To force specific values while the rest
|
||||
with InvisiblePlaywright(
|
||||
seed=42,
|
||||
pin={
|
||||
"gpu.renderer": "ANGLE (NVIDIA, NVIDIA GeForce RTX 4090 Direct3D11)",
|
||||
"gpu.vendor": "Google Inc. (NVIDIA)",
|
||||
"gpu.renderer": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0, D3D11)",
|
||||
"gpu.vendor": "Google Inc. (AMD)",
|
||||
"screen.width": 2560,
|
||||
"screen.height": 1440,
|
||||
"hardware.concurrency": 16,
|
||||
@@ -166,6 +137,11 @@ with InvisiblePlaywright(
|
||||
...
|
||||
```
|
||||
|
||||
A GPU pin picks one of the validated personas rather than setting a free string,
|
||||
because the ~81 `getParameter` values and the extension list travel with the
|
||||
renderer name and a detector cross-checks them against it. A name the pool does
|
||||
not carry raises, and the error lists the ones it does.
|
||||
|
||||
Full list of pinnable keys, how pinning interacts with the Bayesian sampler, and common patterns are in **[docs/pinning.md](docs/pinning.md)**.
|
||||
|
||||
---
|
||||
@@ -184,6 +160,16 @@ invisible-playwright version # wrapper, core and engine versions, and where the
|
||||
|
||||
## Documentation, guides and comparisons
|
||||
|
||||
**If you would rather prompt than script.** This page is the engine, as a Python
|
||||
library. Two ways to use it without writing code, both 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); or 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.
|
||||
|
||||
All of it reads better, and is searchable, in
|
||||
**[the wiki](https://github.com/feder-cr/invisible_playwright/wiki)**,
|
||||
organised into four sections instead of one flat list:
|
||||
@@ -217,17 +203,6 @@ read from its own documentation or from confirmed reverse engineering:
|
||||
[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
|
||||
- [measureText and TextMetrics as a fingerprinting surface](docs/measuretext-textmetrics-fingerprinting.md) - ten-plus numbers from one call needing no permission prompt, and the two mistakes we made fixing it
|
||||
- [What privacy.resistFingerprinting really does](docs/resist-fingerprinting.md) - and why this project sets it to false on purpose
|
||||
- [The ChromeDriver cdc_ variable](docs/cdc-variable-explained.md) - why renaming it is not removing it, and what that generalises to
|
||||
- [What bot.sannysoft.com actually checks](docs/sannysoft-explained.md) - row by row, and the canvas-in-iframe test nobody reads
|
||||
- [How CreepJS decides you are lying](docs/creepjs-explained.md) - four detection techniques, and why blocking the probe is itself recorded
|
||||
- [Firefox preferences that silently do nothing](docs/firefox-prefs-not-applying.md) - five reasons, starting with the one that cost us a real bug
|
||||
- [What BotD actually detects](docs/botd-explained.md) - twenty detectors, and why most are not about bots at all
|
||||
- [Why a FingerprintJS visitor ID changes](docs/fingerprintjs-visitor-id.md) - it is a hash of 41 components, so one moving moves all of it
|
||||
|
||||
## Related projects
|
||||
|
||||
@@ -242,29 +217,66 @@ two around it are how most people reach it:
|
||||
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.
|
||||
**The open-source neighbours.** Which one fits depends on the layer your problem is
|
||||
at, and on whether you need Firefox or Chromium:
|
||||
[three ways to make Playwright undetected](docs/playwright-stealth-levels.md) works
|
||||
through what each layer can reach, and [AI browser agents and stealth](docs/ai-browser-agents-stealth.md)
|
||||
covers the frameworks that pick Chromium over CDP for you.
|
||||
|
||||
**On the Firefox side**
|
||||
|
||||
- **[Camoufox](https://github.com/daijro/camoufox)** - an anti-detect Firefox that also patches at the C++ level. It covers a wider surface and ships its own fingerprint database; this project derives a fingerprint from a seed with a Bayesian sampler, so one number reproduces one machine. [Full comparison](docs/vs-camoufox.md).
|
||||
- **[LibreWolf](https://librewolf.net)** - a Firefox fork with privacy defaults. It ships a configured binary for people to browse with; this ships source patches plus an automation wrapper.
|
||||
- **[arkenfox/user.js](https://github.com/arkenfox/user.js)** - Firefox hardening through preferences. Where a preference is enough, use it; this project patches C++ where one is not.
|
||||
- **[Camoufox](https://github.com/daijro/camoufox)** - patches C++ too, wider surface, ships a fingerprint database instead of deriving one from a seed. [Comparison](docs/vs-camoufox.md).
|
||||
- **[LibreWolf](https://librewolf.net)** - a privacy-defaults Firefox to browse with, not to automate.
|
||||
- **[arkenfox/user.js](https://github.com/arkenfox/user.js)** - hardening through preferences. Where a preference is enough, use it.
|
||||
|
||||
**On the Chromium side**
|
||||
|
||||
- **[Patchright](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright)** - a patched Playwright fork, so the stealth work lands in the driver rather than in the browser binary. [Full comparison](docs/vs-patchright.md).
|
||||
- **[nodriver](https://github.com/ultrafunkamsterdam/nodriver)** - the successor to `undetected-chromedriver`, driving Chrome over CDP directly and removing the WebDriver-flavoured tells. [Full comparison](docs/vs-nodriver.md).
|
||||
- **[playwright-stealth](https://github.com/Mattwmaster58/playwright_stealth)** - an init-script patch applied before the page loads. Its own maintainer calls it a proof-of-concept; [full comparison](docs/vs-playwright-stealth.md).
|
||||
- **[puppeteer-extra-plugin-stealth](https://github.com/berstend/puppeteer-extra)** - the original of this init-script lineage, still widely recommended. Its repository's last substantive commit is from mid-2024; [what that means in practice](docs/puppeteer-extra-stealth-unmaintained.md).
|
||||
- **[selenium-stealth](https://github.com/diprajpatra/selenium-stealth)** - the same approach on Selenium/CDP. Its repository's last commit is from December 2021; [what that means in practice](docs/selenium-stealth-unmaintained.md).
|
||||
- **[pyppeteer](https://github.com/pyppeteer/pyppeteer)** - the unofficial Python port of Puppeteer. Its own README says it's unmaintained and points to `playwright-python` instead; [what that recommendation is actually about](docs/pyppeteer-unmaintained-playwright.md).
|
||||
- **[rebrowser-patches](https://github.com/rebrowser/rebrowser-patches)** - fixes the `Runtime.enable` CDP leak on Chromium, independently converging on close to the same fix Patchright uses. [Full comparison](docs/vs-rebrowser-patches.md).
|
||||
- **[fingerprint-suite](https://github.com/apify/fingerprint-suite)** - generates a coherent fingerprint with a Bayesian network, close to this project's own generation approach, then injects it into a Playwright or Puppeteer page on either Chromium or Firefox. [Full comparison](docs/vs-fingerprint-suite.md).
|
||||
- **[playwright-with-fingerprints](https://github.com/bablosoft/playwright-with-fingerprints)** - injects fingerprint values sourced from a remote paid service, Windows-only, pinned to a specific Chromium build. [Full comparison](docs/vs-playwright-with-fingerprints.md).
|
||||
- **[Patchright](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright)** - a patched Playwright fork: the work lands in the driver, not the binary. [Comparison](docs/vs-patchright.md).
|
||||
- **[nodriver](https://github.com/ultrafunkamsterdam/nodriver)** - successor to `undetected-chromedriver`, driving Chrome over CDP. [Comparison](docs/vs-nodriver.md).
|
||||
- **[rebrowser-patches](https://github.com/rebrowser/rebrowser-patches)** - fixes the `Runtime.enable` CDP leak. [Comparison](docs/vs-rebrowser-patches.md).
|
||||
- **[fingerprint-suite](https://github.com/apify/fingerprint-suite)** - a Bayesian fingerprint generator, then injected into the page. [Comparison](docs/vs-fingerprint-suite.md).
|
||||
- **[playwright-with-fingerprints](https://github.com/bablosoft/playwright-with-fingerprints)** - values from a paid remote service, Windows-only. [Comparison](docs/vs-playwright-with-fingerprints.md).
|
||||
- **[playwright-stealth](https://github.com/Mattwmaster58/playwright_stealth)** - an init-script patch; its maintainer calls it a proof-of-concept. [Comparison](docs/vs-playwright-stealth.md).
|
||||
- **[puppeteer-extra-plugin-stealth](https://github.com/berstend/puppeteer-extra)** - the original of that lineage, last substantive commit mid-2024. [What that means](docs/puppeteer-extra-stealth-unmaintained.md).
|
||||
- **[selenium-stealth](https://github.com/diprajpatra/selenium-stealth)** - the same approach on Selenium, last commit December 2021. [What that means](docs/selenium-stealth-unmaintained.md).
|
||||
- **[pyppeteer](https://github.com/pyppeteer/pyppeteer)** - unmaintained by its own README, which points to `playwright-python`. [What that recommendation is about](docs/pyppeteer-unmaintained-playwright.md).
|
||||
|
||||
Which of these fits depends on the layer your problem is at, and on whether you need Firefox or Chromium. [Three ways to make Playwright undetected](docs/playwright-stealth-levels.md) works through what each layer can and cannot reach, including what this one costs.
|
||||
---
|
||||
|
||||
If you are picking between engines rather than tools, note that a large share of AI agent frameworks drive Chromium over CDP, which decides the question for you: [AI browser agents and stealth](docs/ai-browser-agents-stealth.md).
|
||||
## What is patched in the engine
|
||||
|
||||
Two rules hold across everything below. Every value is decided **before a page can
|
||||
ask**, inside the browser, so there is no JavaScript shim to find. And every value
|
||||
comes from **one profile**, so no two surfaces contradict each other, which is how a
|
||||
spoofed browser is usually caught. Source:
|
||||
[feder-cr/firefox_antidetect_patch](https://github.com/feder-cr/firefox_antidetect_patch).
|
||||
|
||||
**Identity**
|
||||
- `navigator`, the user agent and the client hints are derived together, so they cannot disagree: [does Playwright set navigator.webdriver](docs/does-playwright-set-navigator-webdriver.md), [client hints and Sec-Fetch](docs/client-hints-sec-fetch.md).
|
||||
- `navigator.languages` and the `Accept-Language` header are the same declaration, sent and read: [Accept-Language and navigator.languages](docs/accept-language-navigator-languages.md).
|
||||
- Screen geometry, `devicePixelRatio` and the media queries exposing it are declared, not read from the host: [devicePixelRatio and the Firefox pref](docs/devicepixelratio-firefox-pref.md), [CSS media query fingerprinting](docs/css-media-query-fingerprinting.md).
|
||||
|
||||
**Rendering**
|
||||
- Canvas readback is deterministic per seed and keeps the real shape, rather than blocked or noised: [canvas fingerprint noise](docs/canvas-fingerprint-noise.md), [why a canvas fingerprint changes every run](docs/canvas-fingerprint-changes-every-run.md).
|
||||
- WebGL reports a coherent GPU persona: vendor, renderer and the parameter limits are cross-checked, not set one at a time: [WebGL renderer strings](docs/webgl-renderer-strings.md), [WebGL parameters are identical](docs/webgl-parameters-are-identical.md).
|
||||
- Fonts ship with the browser, so the same faces exist on every host and the platform font engine no longer chooses: [bundled fonts across platforms](docs/bundled-fonts-cross-platform.md), [why headless browsers render different fonts](docs/headless-fonts-differ.md), [detecting installed fonts from JavaScript](docs/detect-installed-fonts-javascript.md).
|
||||
- Text metrics follow those fonts: `measureText` returns ten-plus numbers from one call, with no permission prompt: [measureText and TextMetrics](docs/measuretext-textmetrics-fingerprinting.md).
|
||||
- Canvas and WebGL agree across operating systems for the same seed: [cross-platform consistency](docs/canvas-webgl-cross-platform-consistency.md), [canvas differs across operating systems](docs/canvas-differs-across-operating-systems.md).
|
||||
|
||||
**Audio and media**
|
||||
- The audio stack answers from the profile rather than from the host device: [AudioContext fingerprinting](docs/audiocontext-fingerprinting.md), [sample rate and latency](docs/audiocontext-samplerate-latency-fingerprint.md).
|
||||
- The codec table is declared, so a Linux host does not answer a Windows question with Linux support: [codec fingerprinting](docs/codec-fingerprinting.md).
|
||||
|
||||
**Network**
|
||||
- WebRTC offers one synthetic candidate carrying the proxy exit, instead of leaking the real address or offering none, which is itself a tell: [WebRTC ICE candidate spoofing](docs/webrtc-ice-candidate-spoofing.md), [does the WebRTC IP match the proxy exit](docs/webrtc-ip-match-proxy-exit.md).
|
||||
- DNS resolves through the proxy, including when the proxy is not in the preferences: [does a proxy leak DNS](docs/does-a-proxy-leak-dns-doh-explained.md), [how to check for a proxy IP leak](docs/how-to-check-proxy-ip-leak.md).
|
||||
- The timezone comes from the egress IP, resolved offline, so it matches the exit: [timezone and proxy mismatch](docs/timezone-proxy-mismatch.md), [offline GeoIP timezone](docs/offline-geoip-timezone-proxy.md).
|
||||
|
||||
**The automation layer**
|
||||
- Input events come from the real input path, so `isTrusted` is true because it is true: [Playwright clicks and isTrusted](docs/playwright-clicks-istrusted.md).
|
||||
- The pointer follows a human path and timing, at a cadence a real device could produce: [human mouse movement](docs/human-mouse-movement.md), [mouse dynamics as behavioural biometrics](docs/mouse-dynamics-behavioural-biometrics.md).
|
||||
- The debugger surface does not answer the timing questions that give a driven browser away: [debugger timing detection](docs/debugger-timing-detection.md).
|
||||
- Closed-mode shadow roots are reachable, which stock Playwright cannot do in either engine, while the page still reads `null`: [closed shadow roots](docs/closed-shadow-root-playwright.md).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
---
|
||||
title: "Alternative Chromium browsers for automation: what differs"
|
||||
description: "Brave, Edge, Opera, Vivaldi, Ungoogled: what actually changes between the forks, and why none of it touches the CDP tells that really decide detection."
|
||||
parent: "Comparisons"
|
||||
nav_order: 40
|
||||
---
|
||||
|
||||
# Alternative Chromium browsers for automation, and the one question that matters
|
||||
|
||||
Brave, Microsoft Edge, Opera, Vivaldi, Ungoogled Chromium: all of them build on
|
||||
the open-source Chromium project, and all of them are Chromium for automation
|
||||
purposes in the way that matters most. This page is about what actually
|
||||
changes between the forks, and the one thing that does not.
|
||||
|
||||
## What Chromium being the base actually means
|
||||
|
||||
Every fork above takes Chromium's rendering engine (Blink), its JavaScript
|
||||
engine (V8), and most of its automation surface (CDP, the same protocol
|
||||
Playwright and Puppeteer speak to Chrome) largely unchanged. What each fork
|
||||
adds is UI chrome, some default settings, and in a couple of cases genuine
|
||||
engine-level changes - which is the part that matters and the part most
|
||||
comparisons skip.
|
||||
|
||||
## What actually differs
|
||||
|
||||
**Ungoogled Chromium** strips Google-service integration and telemetry calls.
|
||||
The rendering and automation surface underneath is stock Chromium. For
|
||||
detection purposes this changes almost nothing observable from a page; it
|
||||
changes what phones home, not what the DOM reports.
|
||||
|
||||
**Brave** adds a built-in ad and tracker blocker and fingerprinting
|
||||
countermeasures aimed at *passive, cross-site* tracking - randomizing certain
|
||||
canvas and audio outputs per session by default. That is a genuine engine-level
|
||||
difference, and it cuts both ways for automation: it can make canvas-based
|
||||
fingerprint matching noisier, but a browser that randomizes its own canvas
|
||||
output on every load is itself an unusual, identifiable behaviour to a detector
|
||||
that checks for consistency across repeat visits.
|
||||
|
||||
**Edge, Opera, Vivaldi** are UI and feature layers - vertical tabs, built-in
|
||||
VPNs, sidebar panels - on essentially stock Chromium/Blink underneath, with UA
|
||||
strings that identify them as themselves rather than as Chrome.
|
||||
|
||||
## The one question that matters, and none of these answer it
|
||||
|
||||
**Is the browser being driven by an automation protocol, and does that show?**
|
||||
Every fork above, driven by Playwright or Puppeteer over [CDP](bidi-vs-cdp-detection.md),
|
||||
inherits the same automation surface Chrome does, because CDP is the layer
|
||||
Playwright actually talks to - the browser skin on top is close to irrelevant
|
||||
to what CDP exposes. [`navigator.webdriver`](navigator-webdriver-explained.md),
|
||||
the CDP-specific runtime properties, the automation flags: present in
|
||||
Brave-under-Playwright exactly as in Chrome-under-Playwright, because they
|
||||
come from the driving protocol, not the fork.
|
||||
|
||||
Picking a different Chromium skin to solve a detection problem is picking a
|
||||
different paint color to fix an engine problem. The tells that matter live in
|
||||
the automation layer, not in whether the tab bar says Brave or Edge.
|
||||
|
||||
## Where the fork does matter
|
||||
|
||||
- **Feature availability for your test surface.** If you are testing behaviour
|
||||
specific to Edge's rendering quirks or Brave's Shields, you need that
|
||||
specific browser, automation-detectability aside.
|
||||
- **A UA string that must say the right thing.** If a site branches logic on
|
||||
the UA rather than on capability detection, the fork's declared identity
|
||||
matters for that reason alone.
|
||||
- **Brave's own fingerprint randomization**, if you specifically want noisier
|
||||
canvas/audio output and are not worried about the randomization itself being
|
||||
a signal.
|
||||
|
||||
## The actual alternative, if the browser is your problem
|
||||
|
||||
If what you are after is a Chromium-family browser that reads as a normal
|
||||
consumer install rather than an automation-driven one, the fork choice is the
|
||||
wrong lever - the automation layer is. [Patchright](vs-patchright.md) takes
|
||||
this approach on Chromium specifically: patching Playwright's driver to
|
||||
remove the most common CDP-level tells rather than switching which skin sits
|
||||
on top.
|
||||
|
||||
This project takes the same idea on a different base entirely: a Firefox
|
||||
patched at the C++ source, chosen over any Chromium fork because Firefox is
|
||||
not driven over CDP at all - a different protocol with a different, smaller
|
||||
set of shared tells, on an engine most anti-bot vendors have spent
|
||||
proportionally less effort fingerprinting given Chromium's dominant share.
|
||||
[Firefox or Chromium for anti-detect automation](firefox-vs-chromium-antidetect.md)
|
||||
is the fuller argument for that choice, independent of which Chromium fork you
|
||||
were comparing against.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Is Brave harder to detect than Chrome for automation?** Not meaningfully,
|
||||
when driven by the same protocol. Its fingerprint randomization changes canvas
|
||||
and audio output but does not touch the automation-protocol signals a detector
|
||||
checks first.
|
||||
|
||||
**Does using Edge instead of Chrome avoid bot detection?** No. Same Blink
|
||||
engine, same CDP surface when automated, different UA and UI.
|
||||
|
||||
**Is there a Chromium fork built for automation stealth?** Not among the
|
||||
consumer forks above. Patchright and undetected-chromedriver-style projects
|
||||
patch the driver layer on stock Chromium/Chrome rather than relying on a
|
||||
different skin.
|
||||
|
||||
**Does Ungoogled Chromium avoid fingerprinting?** It removes Google telemetry
|
||||
calls, not fingerprintable page-level properties. A detection script reads the
|
||||
same DOM and JS surface either way.
|
||||
|
||||
**Which non-Chromium browser is worth trying instead?** Firefox is the
|
||||
structurally different option - different rendering engine, different
|
||||
automation protocol - which is the actual axis that moves the needle rather
|
||||
than a Chromium skin.
|
||||
|
||||
**See also:**
|
||||
[Firefox or Chromium for anti-detect automation](firefox-vs-chromium-antidetect.md),
|
||||
[patchright vs invisible_playwright](vs-patchright.md) for the driver-patching
|
||||
approach on Chromium, and
|
||||
[what navigator.webdriver really tells a site](navigator-webdriver-explained.md)
|
||||
for the flag every CDP-driven fork inherits alike.
|
||||
|
||||
## Sources
|
||||
|
||||
- [The Chromium Project](https://www.chromium.org/chromium-projects/), retrieved 2026-09-10, for what the open-source base provides to every fork.
|
||||
- [Brave's own documentation on fingerprinting protections](https://brave.com/privacy-features/), retrieved 2026-09-10, for the canvas/audio randomization behaviour described above.
|
||||
- [Chrome DevTools Protocol documentation](https://chromedevtools.github.io/devtools-protocol/), retrieved 2026-09-10, for the automation surface every CDP-driven Chromium fork exposes identically.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
a Firefox patched at the C++ level, precisely because a Chromium fork does not
|
||||
change the automation protocol underneath it. The page recommends switching
|
||||
engines rather than skins for that reason, and says so plainly rather than
|
||||
implicitly.*
|
||||
@@ -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, not practitioner reconstruction. Say that plainly, because it is the exception in this corpus, not the rule.
|
||||
Every other vendor in [the survey of how websites detect bots](how-do-websites-detect-bots.md) 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.
|
||||
|
||||
@@ -27,7 +27,7 @@ Later versions moved Anubis toward something closer to a lightweight, rule-drive
|
||||
|
||||
## Adoption: this is not a hypothetical
|
||||
|
||||
Anubis is deployed in front of real infrastructure at meaningful scale, not just a research demo. Documented adopters include GNOME's GitLab instance, the Linux kernel's mailing list and Git infrastructure, FFmpeg, Wine, UNESCO, FreeCAD, ScummVM, Duke University's digital archives, OpenWRT, and the Deutsche Nationalbibliothek. Its author's own stated tradeoff is explicit rather than hidden: deploying it "will result in your website being blocked from smaller scrapers and may inhibit 'good bots' like the Internet Archive," and the project's guidance is that most sites should try Cloudflare first and reach for Anubis only when that is not an option.
|
||||
Anubis is deployed in front of real infrastructure at meaningful scale, not just a research demo. Documented adopters include GNOME's GitLab instance, the Linux kernel's mailing list and Git infrastructure, FFmpeg, Wine, UNESCO, FreeCAD, ScummVM, Duke University's digital archives, OpenWRT, and the Deutsche Nationalbibliothek. Its author's own stated tradeoff is explicit rather than hidden: deploying it "will result in your website being blocked from smaller scrapers and may inhibit 'good bots' like the Internet Archive," and the project's guidance is that most sites should try Cloudflare first and reach for Anubis only when that is not an option, which in practice means the gate a visitor meets is more often [Turnstile](cloudflare-turnstile-explained.md) than this one.
|
||||
|
||||
## A real, named critique worth reading in full
|
||||
|
||||
@@ -39,7 +39,7 @@ That critique does not contradict what Anubis's own author and documentation say
|
||||
|
||||
This is the one detector in this whole corpus where the honest answer is: engine realness is close to irrelevant to whether the gate opens. Anubis is not testing whether a browser is lying about its fingerprint, checking canvas output, or looking for automation-framework tells. It is testing one thing: can this client execute a modern JavaScript engine fast enough to solve a SHA-256 search in a reasonable time. Any real browser, patched or unpatched, stealth or not, answers that the same way, because the puzzle does not touch fingerprint surfaces at all. A plain HTTP client with no JavaScript engine fails it regardless of how convincingly its headers are spoofed, which is the entire point: it is a liveness test for "do you run JavaScript like a browser," not a fidelity test for "are you the specific browser you claim to be."
|
||||
|
||||
`invisible_playwright` does not do anything specific to Anubis, and there is nothing Anubis-specific to do: a genuinely real Firefox, C++-patched or stock, solves its puzzle the same way any other real Firefox does, because the puzzle is engine-agnostic by construction. What this page is really useful for is the opposite lesson: not every gate in this space is a fingerprint problem, and treating Anubis as one would be a category error.
|
||||
`invisible_playwright` does not do anything specific to Anubis, and there is nothing Anubis-specific to do: a genuinely real Firefox, C++-patched or stock, solves its puzzle the same way any other real Firefox does, because the puzzle is engine-agnostic by construction. What this page is really useful for is the opposite lesson: not every gate in this space is a fingerprint problem, and treating Anubis as one would be a category error. The gates that do read [what a browser fingerprint is made of](what-is-a-browser-fingerprint.md) are a separate family, and knowing which of the two you are behind decides whether any of that work applies at all.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
|
||||
@@ -89,6 +89,21 @@ as [what `navigator.vendor` and `navigator.productSub` report on Firefox](naviga
|
||||
which are wrong on a Chromium base pretending to be Firefox and correct on an actual
|
||||
Firefox build.
|
||||
|
||||
### The answer, read from a session
|
||||
|
||||

|
||||
|
||||
`navigator.getBattery` is `undefined`, which is the answer to the title, and the bundled
|
||||
Firefox returns the same thing.
|
||||
|
||||
The two Firefox constants sit next to it on purpose. A build that reports the empty
|
||||
`vendor` and `20100101` for `productSub`, and then hands a page a battery object, has
|
||||
contradicted itself with three property reads: the first two say Firefox and the third
|
||||
says something that is not one.
|
||||
|
||||
## Check it yourself in two lines
|
||||
|
||||
Switching from stock Playwright is a two-line change, and after that every standard
|
||||
|
||||
@@ -92,20 +92,21 @@ anyone who needs it.
|
||||
|
||||
The cost is real and you should know it before you enable this anywhere:
|
||||
|
||||
**[`go_back()`](https://playwright.dev/python/docs/api/class-page#page-go-back) waiting
|
||||
for `load` can time out.** A bfcache restore does not fire `load`,
|
||||
because nothing loaded. Code that navigates back and waits for that event will sit there
|
||||
until the timeout expires.
|
||||
**`go_back()` used to time out here, and does not any more.** A bfcache restore does not
|
||||
fire `load`, so code waiting for that event sat there until the deadline. The engine
|
||||
reports the navigation from firefox-31, and the driver stopped caching the injected
|
||||
script across a restore in 0.19.0, which was the second half of the same problem: the
|
||||
page came back and the driver was still holding a handle into the world it had left.
|
||||
|
||||
```python
|
||||
# fragile once bfcache is enabled
|
||||
page.go_back() # may wait for a load that never comes
|
||||
|
||||
# robust either way
|
||||
page.go_back(wait_until="domcontentloaded")
|
||||
# fine now
|
||||
page.go_back()
|
||||
page.wait_for_selector("#something-on-the-previous-page")
|
||||
```
|
||||
|
||||
Waiting for something you can see is still more robust than waiting for a lifecycle
|
||||
event on a restore, because the lifecycle events genuinely do not fire again.
|
||||
|
||||
Waiting for something you can see is more robust than
|
||||
[waiting for a lifecycle event](how-to-wait-for-page-load-playwright.md) anyway, and it
|
||||
works whether or not the page was restored.
|
||||
@@ -151,8 +152,9 @@ in Firefox explicitly and in Chromium effectively.
|
||||
never restore, which is not how consumer browsers behave. It is a weak signal on its own
|
||||
and it belongs to a family of weak behavioural signals.
|
||||
|
||||
**Why does `go_back()` hang after I enable bfcache?** Because a restore does not fire
|
||||
`load`. Wait for `domcontentloaded` or for an element instead.
|
||||
**Does `go_back()` still hang?** No, since firefox-31 for the navigation and 0.19.0 for
|
||||
the driver side. Wait for an element rather than for `load`, which does not fire again
|
||||
on a restore.
|
||||
|
||||
**Should I enable it?** For realistic sessions yes, for deterministic test suites
|
||||
probably not.
|
||||
@@ -174,7 +176,7 @@ for where behavioural signals sit in the wider picture.
|
||||
and [MDN: the `pageshow` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event),
|
||||
which documents `persisted`.
|
||||
- Playwright's documented [`go_back()`](https://playwright.dev/python/docs/api/class-page#page-go-back)
|
||||
and its `wait_until` values, including `domcontentloaded`.
|
||||
and its `wait_until` values.
|
||||
- The Playwright tracker's open items on bfcache behaviour and on enabling it under
|
||||
Chromium.
|
||||
- This project's driver, which reads a preference before disabling the cache and leaves
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
---
|
||||
title: "Browser automation testing tools: where each one fits"
|
||||
description: "Playwright, Selenium, Cypress and Puppeteer by what each one was built to test, not by feature count, plus the axis none of the four was designed around."
|
||||
parent: "Comparisons"
|
||||
nav_order: 41
|
||||
---
|
||||
|
||||
# Browser automation testing tools, and where each one actually fits
|
||||
|
||||
Four names come up constantly and get compared as if they were interchangeable:
|
||||
Playwright, Selenium, Cypress and Puppeteer. They overlap enough to confuse
|
||||
and differ enough that picking by feature-list length is how people end up
|
||||
fighting the wrong tool for a year.
|
||||
|
||||
## The four, by what they are actually built for
|
||||
|
||||
**Playwright.** General-purpose, cross-browser (Chromium, Firefox, WebKit),
|
||||
built by Microsoft with auto-waiting and multi-language support (JS/TS,
|
||||
Python, Java, .NET). The current default recommendation for new
|
||||
browser-automation projects that need real cross-browser coverage.
|
||||
|
||||
**Selenium.** The oldest and most widely deployed, via the W3C WebDriver
|
||||
standard. Broadest language support, largest historical ecosystem, and the
|
||||
one that can drive an actual retail browser install rather than a
|
||||
framework-maintained build - relevant if you specifically need to test
|
||||
against exactly what your users have installed.
|
||||
|
||||
**Cypress.** Built specifically for testing web applications from inside the
|
||||
browser, running in the same run-loop as your app rather than driving it from
|
||||
outside. Excellent developer experience and debugging for single-page apps,
|
||||
historically Chromium-only in practice (with newer versions adding limited
|
||||
Firefox and WebKit support), and architecturally not built for the kind of
|
||||
cross-origin, multi-tab scraping work Playwright and Selenium both handle
|
||||
natively.
|
||||
|
||||
**Puppeteer.** Chromium/Chrome only, Node.js only, maintained by the Chrome
|
||||
team. If your target is specifically Chrome and your stack is Node, it is a
|
||||
direct, well-supported option; it does not cover Firefox or WebKit at all.
|
||||
|
||||
## Choosing by what you are actually testing
|
||||
|
||||
| Your situation | Reach for |
|
||||
|---|---|
|
||||
| Cross-browser regression suite, multiple languages on the team | Playwright |
|
||||
| Testing a Chrome-only internal app, Node stack already in place | Puppeteer |
|
||||
| Fast-feedback testing of a single-page app you are actively developing | Cypress |
|
||||
| Must drive an actual retail-installed browser, not a framework build | Selenium |
|
||||
| Large legacy Selenium suite that works | Selenium, don't rewrite for its own sake |
|
||||
| Real-world scraping across multiple sites, need Firefox specifically | Playwright |
|
||||
|
||||
## The axis none of these four are built around
|
||||
|
||||
All four of these are testing tools, built to verify that **your own
|
||||
application** behaves correctly under known, cooperative conditions. None of
|
||||
them was designed against a page actively trying to distinguish automation
|
||||
from a human - because for their primary use case, the page being tested is
|
||||
yours, and it has no reason to fight you.
|
||||
|
||||
That changes completely when the target is someone else's site and it is
|
||||
actively fingerprinting. Every one of these four, used with its default
|
||||
browser build, presents recognizable automation signals: `navigator.webdriver`
|
||||
under WebDriver-based tools, CDP-visible properties under CDP-driven ones,
|
||||
and browser builds that differ from a retail install in ways a determined
|
||||
detector checks for. Picking Playwright over Selenium, or Puppeteer over
|
||||
Cypress, does not change this axis at all - it is orthogonal to which testing
|
||||
tool you picked.
|
||||
|
||||
## Where this project sits
|
||||
|
||||
[invisible_playwright](https://github.com/feder-cr/invisible_playwright) is
|
||||
not a fifth entry on the list above competing for the same job. It answers a
|
||||
different question: given that you have already picked Playwright's API
|
||||
(unchanged, same code you would write against any Playwright browser), what
|
||||
if the Firefox underneath it was patched at the C++ source rather than
|
||||
Playwright's stock automation build? It is the engine layer beneath a testing
|
||||
tool, not a replacement for one.
|
||||
[Firefox or Chromium for anti-detect automation](firefox-vs-chromium-antidetect.md)
|
||||
covers why Firefox was the base worth patching, and
|
||||
[patchright vs invisible_playwright](vs-patchright.md) covers the equivalent
|
||||
idea applied to Chromium instead.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Is Playwright better than Selenium?** For new cross-browser projects,
|
||||
usually yes - faster, auto-waiting, fewer moving parts. Selenium's breadth of
|
||||
language support and ability to drive a real retail browser remain real
|
||||
advantages in specific cases.
|
||||
|
||||
**Is Cypress a replacement for Selenium or Playwright?** Not a direct one.
|
||||
Cypress is purpose-built for testing an application you control from inside
|
||||
the browser's run-loop, and is a weaker fit for cross-origin scraping or
|
||||
multi-tab flows that Selenium and Playwright handle natively.
|
||||
|
||||
**Does Puppeteer support Firefox?** Puppeteer has had experimental Firefox
|
||||
support at various points; it is not the primary, well-maintained target the
|
||||
way Chrome is. If Firefox specifically matters, Playwright is the
|
||||
better-supported cross-browser option.
|
||||
|
||||
**Which tool is hardest to detect?** None of the four is built with detection
|
||||
resistance as a design goal, and the default automation build under any of
|
||||
them is recognizable. That is a separate axis from which testing tool fits
|
||||
your testing needs.
|
||||
|
||||
**Can I use these for scraping instead of testing?** Yes, and Playwright and
|
||||
Selenium in particular are commonly used this way - but recognize that you
|
||||
have moved outside each tool's primary design intent, onto an axis (adversarial
|
||||
detection) none of them was built to address.
|
||||
|
||||
**See also:**
|
||||
[Selenium vs Playwright: the actual differences](difference-between-selenium-and-playwright.md),
|
||||
[Migrating from Puppeteer to Playwright for stealth](migrate-puppeteer-to-playwright-stealth.md),
|
||||
and [Firefox or Chromium for anti-detect automation](firefox-vs-chromium-antidetect.md).
|
||||
|
||||
## Sources
|
||||
|
||||
- [Playwright's own documentation](https://playwright.dev/), [Selenium's documentation](https://www.selenium.dev/documentation/), [Cypress's documentation](https://docs.cypress.io/), and [Puppeteer's documentation](https://pptr.dev/), all retrieved 2026-09-10, for each project's stated scope and browser support.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
which is not a competitor to any of the four tools above - it sits underneath
|
||||
one of them. The page is organized around picking the right testing tool
|
||||
first, because that decision is independent of the engine question it exists
|
||||
to answer.*
|
||||
@@ -81,6 +81,21 @@ a real AudioContext output, and Windows screen metrics with a plausible availabl
|
||||
and device pixel ratio. Those answers are the same whether the host is your laptop or a
|
||||
Linux container, because they are presented by the browser rather than read from the box.
|
||||
|
||||
## What each browser answers on the same page
|
||||
|
||||

|
||||
|
||||
Three values from one page served from `127.0.0.1`. The audio sample rate is `48000 Hz`
|
||||
in both browsers and the platform string is `Win32` in both, so neither of those two is
|
||||
the server tell on this host.
|
||||
|
||||
That is worth showing precisely because the section above is about a machine looking
|
||||
like a server rather than a desktop. On a real desktop with a real audio device the
|
||||
sample rate is ordinary in both, and the value that separates the two runs is the
|
||||
automation flag, which is not a server signal at all.
|
||||
|
||||
## What invisible_playwright presents instead
|
||||
|
||||
The launch is two lines, and the browser you get back is a real Playwright
|
||||
|
||||
@@ -80,6 +80,22 @@ the folder.
|
||||
This is not a bug in private mode. Private mode never promised a new identity. It
|
||||
promised no leftover state, and it delivers that.
|
||||
|
||||
## What changes when the values change
|
||||
|
||||

|
||||
|
||||
Three values, read from one page served from `127.0.0.1`. `localStorage` is available in
|
||||
both, which is the point of the section above: private mode is about state, and this
|
||||
probe is not reading state.
|
||||
|
||||
The line that moves is the canvas, hashed from `getImageData` bytes rather than from
|
||||
`toDataURL`, and the reason for that choice is measured in
|
||||
[why a canvas hash changes between runs](canvas-fingerprint-changes-every-run.md): the
|
||||
encoded string moves on its own even when the pixels do not.
|
||||
|
||||
## Changing the values themselves, not clearing storage
|
||||
|
||||
If the problem is that the fingerprint values are stable and readable, the fix is to
|
||||
|
||||
@@ -33,8 +33,11 @@ audio pipeline draw the same thing every time.
|
||||
|
||||
In this browser, those three readbacks are overwritten before they reach your code.
|
||||
The value you read is a pure function of one number: an internal hardware seed the
|
||||
wrapper derives from the identity seed of the session. Same seed in, same bytes out.
|
||||
Different seed, different bytes.
|
||||
wrapper derives from the identity seed of the session. Same seed in, same bytes out,
|
||||
which is the direction you can rely on. The reverse does not hold as neatly: two
|
||||
different identity seeds can land on the same hardware seed and hand you the same
|
||||
readback, so a changed seed is not a guarantee of changed bytes. If you need two
|
||||
sessions to look like two machines, check the readback rather than assuming it.
|
||||
|
||||
So when you launch without passing a seed, each session gets a new one, and the three
|
||||
hashes move together in a self-consistent way. That is not the spoof failing. That is
|
||||
@@ -123,6 +126,47 @@ pages is that you [assert the presence of the right value rather than the absenc
|
||||
wrong one](how-to-test-bot-detection.md), and this is a case where you can measure the
|
||||
right value directly.
|
||||
|
||||

|
||||
|
||||
Four sessions above, one page served from `127.0.0.1`, hashes computed inside the page
|
||||
so the numbers and the picture come from the same run. The two unseeded sessions
|
||||
disagree on both readbacks. The two seeded ones agree on both, and their screenshots
|
||||
are identical pixel for pixel, 0 of 79,800 differing.
|
||||
|
||||
The detail worth noticing is that the drawing looks the same in all four panels. Your
|
||||
eye cannot separate them; the hash separates them immediately. That is the shape of
|
||||
this whole surface: the readback is not the picture, and a page that hashes it is not
|
||||
looking at what you are looking at.
|
||||
|
||||
The second unseeded panel is also physically larger, because that session drew at a
|
||||
different device pixel ratio. It is not only the readbacks that get redrawn per
|
||||
session: the device does.
|
||||
|
||||
**Two things about that panel are worth stating precisely, because guessing them wrong
|
||||
sends you debugging the wrong thing.**
|
||||
|
||||
**What changes on every unseeded launch is the device, not necessarily the readback.**
|
||||
Five unseeded launches, reading four values each: the screen alternated between
|
||||
1920x1080 and 2560x1440, the core count between 4 and 12, the device pixel ratio
|
||||
between 1 and 1.25. All five moved. The canvas readback, over the same five launches,
|
||||
returned the same value four times. So **two unseeded runs agreeing on a canvas hash is
|
||||
not evidence that your seed took effect** - it is the likelier outcome. Check a value
|
||||
that varies freely, like the screen or the core count, when you want to know whether a
|
||||
new identity was drawn.
|
||||
|
||||
**And if you hash `toDataURL()`, you are partly hashing the PNG encoder.** On the
|
||||
bundled Firefox, three launches drawing the identical canvas returned three different
|
||||
`toDataURL()` hashes while `getImageData()` returned the same pixel bytes all three
|
||||
times. The pixels never moved; the encoded string did. A canvas hash that changes
|
||||
between two runs of a *stock* browser is usually this, not a fingerprinting defence, and
|
||||
it is not something `privacy.fingerprintingProtection` or `privacy.resistFingerprinting`
|
||||
explains: both were tested off and on, and the encoded string kept moving either way.
|
||||
Compare `getImageData` bytes when you want to know whether the drawing changed.
|
||||
|
||||
Draw to a canvas, read it back with
|
||||
[`toDataURL()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL),
|
||||
and compare the hash across two launches with the same seed:
|
||||
@@ -218,6 +262,12 @@ after launch and log it. Passing that number back reproduces the same device.
|
||||
same cookies but a different fingerprint is a contradiction. Keep one stable seed per
|
||||
durable identity.
|
||||
|
||||
**Should I hash `toDataURL()` or `getImageData()`?** `getImageData`, if you want to know
|
||||
whether the drawing changed. Three launches of the bundled Firefox drawing the same
|
||||
canvas returned three different `toDataURL` hashes and the same pixel bytes every time:
|
||||
the encoded string moves on its own, so a data URL hash reports changes the canvas never
|
||||
made.
|
||||
|
||||
## Sources
|
||||
|
||||
- The project's fingerprint generator, in which the canvas, WebGL and audio readbacks
|
||||
|
||||
@@ -133,6 +133,22 @@ pixel: [`measureText()` and its ten-plus numeric fields](measuretext-textmetrics
|
||||
which fail the same way for the same reason if the noise added to them accumulates
|
||||
instead of staying bounded.
|
||||
|
||||
## Substitution, seen on one page
|
||||
|
||||

|
||||
|
||||
One page served from `127.0.0.1`, three values, two browsers. The canvas pixel hash
|
||||
moves and the text width does not: `measureText` returns `115.65 px` in both.
|
||||
|
||||
That pairing is the distinction this page is built on. A substituted readback changes
|
||||
what comes out of the canvas without changing the layout metrics the same text produces,
|
||||
so a detector comparing the two does not find the mismatch that per-call noise creates.
|
||||
The hash comes from `getImageData` bytes on purpose: `toDataURL` output moves between
|
||||
launches on the bundled browser too, for encoder reasons that have nothing to do with
|
||||
the drawing.
|
||||
|
||||
## Checking your own
|
||||
|
||||
```js
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
---
|
||||
title: "How to check a proxy's status before you rely on it"
|
||||
description: "Liveness, exit location, latency and browser behaviour are four checks, not one. The order to run them, and what none of them can tell you about a site."
|
||||
parent: "Network, Proxy and WebRTC"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 40
|
||||
---
|
||||
|
||||
# How to check a proxy's status before you rely on it
|
||||
|
||||
"Is my proxy working" is actually four separate questions, and treating it as
|
||||
one is how people spend an hour debugging a browser fingerprint when the
|
||||
proxy was down the whole time, or blame a working proxy for a site's own
|
||||
block.
|
||||
|
||||
## The four checks, in the order to run them
|
||||
|
||||
**1. Is it alive at all?** Before touching a browser: `curl` through it and see
|
||||
if you get a response.
|
||||
|
||||
```bash
|
||||
curl -x socks5h://user:pass@host:port https://ifconfig.me
|
||||
```
|
||||
|
||||
`socks5h` (not `socks5`) resolves DNS through the proxy rather than locally,
|
||||
which matters for the leak question below. An HTTP proxy uses
|
||||
`curl -x http://user:pass@host:port ...` instead. If this hangs or errors, stop
|
||||
here - nothing downstream will work and no browser-level fix changes it.
|
||||
|
||||
**2. Where does it say it is exiting from?** The `ifconfig.me` response gives
|
||||
you the exit IP. Check it against a geolocation lookup and against what you
|
||||
expected to pay for. A proxy sold as "US residential" that resolves to a
|
||||
datacenter ASN in a different country is not doing what you bought it for,
|
||||
and this is worth catching before you spend time on anything else.
|
||||
|
||||
**3. Is it fast enough for what you are doing?** `curl -x ... -w "%{time_total}\n" -o /dev/null -s https://example.com`
|
||||
gives you a round-trip number. A proxy that is technically alive but takes
|
||||
eight seconds per request will make an automated flow look nothing like a
|
||||
human's browsing rhythm, independent of any fingerprint concern.
|
||||
|
||||
**4. Does it hold up through an actual browser session, not just curl?** This
|
||||
is the check people skip, and it is where a proxy that passes checks 1-3 can
|
||||
still fail in practice. `curl` and a browser are different clients: a browser
|
||||
opens more connections, resolves DNS differently depending on configuration,
|
||||
and can leak the real address through WebRTC regardless of what the HTTP
|
||||
proxy is doing correctly.
|
||||
[How to check if a proxy leaks your real IP](how-to-check-proxy-ip-leak.md)
|
||||
is the browser-level version of this check, and it is not optional if the
|
||||
proxy's whole purpose is to hide the real address - a proxy that passes
|
||||
`curl` but leaks over WebRTC has not actually done its job.
|
||||
|
||||
## What "proxy status" checks cannot tell you
|
||||
|
||||
None of the four checks above say anything about whether a *site* will let
|
||||
you through. A perfectly healthy, correctly-exiting, fast proxy still gets
|
||||
challenged if the browser behind it reports as automated, or if the exit
|
||||
address has been used by enough other traffic to earn a bad reputation on
|
||||
that specific site's own reputation database. Conflating "my proxy is up" with
|
||||
"the site accepts my proxy's traffic" is a different confusion in the other
|
||||
direction from the one above, and it sends people rotating proxies to fix a
|
||||
browser-fingerprint problem.
|
||||
|
||||
## A quick reference for interpreting results
|
||||
|
||||
| Symptom | Likely cause | Where to look |
|
||||
|---|---|---|
|
||||
| curl through the proxy hangs or errors | Proxy is down or credentials are wrong | Check 1 |
|
||||
| curl works, exit IP is wrong country/ASN | Wrong proxy config or provider issue | Check 2 |
|
||||
| curl works, browser session times out | Browser-specific connection handling, or WebRTC leaking real address and site rejecting the mismatch | Check 4 |
|
||||
| Everything above passes, site still blocks | Fingerprint, rate, or behavioural detection - not the proxy | See below |
|
||||
|
||||
If you have run all four checks and the proxy is confirmed healthy and
|
||||
non-leaking, and you are still being challenged, the proxy has done its job
|
||||
and the remaining problem is elsewhere.
|
||||
[Why does my Playwright script get blocked?](why-does-my-playwright-script-get-blocked.md)
|
||||
is the next page to read, and it starts from exactly this point: address
|
||||
confirmed fine, now what.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**How do I know if my proxy is working?** Run `curl` through it against an IP
|
||||
echo service before touching a browser. If that fails, nothing above it will
|
||||
work either.
|
||||
|
||||
**Why does my proxy work in curl but not in my browser?** Different clients
|
||||
handle DNS and WebRTC differently. A working `curl` test does not rule out a
|
||||
WebRTC leak or a browser-specific connection issue.
|
||||
|
||||
**How often should I check a proxy's status?** Before every automated session
|
||||
that depends on it mattering, if the proxy is shared or rotating - a proxy
|
||||
that worked an hour ago can have changed reputation or gone down since.
|
||||
|
||||
**Does a slow proxy get detected more?** Indirectly: unusually slow, uniform
|
||||
latency is itself a signal in aggregate behavioural analysis, separate from
|
||||
whatever the proxy's address reputation is.
|
||||
|
||||
**Is a datacenter proxy always worse than residential?** Not universally - it
|
||||
depends entirely on whether the specific site treats datacenter ranges
|
||||
differently, which varies by site.
|
||||
|
||||
**See also:**
|
||||
[How to check if a proxy leaks your real IP](how-to-check-proxy-ip-leak.md),
|
||||
[Setting a proxy per Playwright context](set-geolocation-permissions-per-playwright-context.md),
|
||||
and [WebRTC leak with a proxy](webrtc-leak-proxy.md).
|
||||
|
||||
## Sources
|
||||
|
||||
- [Playwright's documented proxy configuration](https://playwright.dev/python/docs/network#http-proxy), retrieved 2026-09-10, for how proxy credentials and per-context proxies are set.
|
||||
- This project's own release gates, including the positive-form WebRTC check referenced in check 4, which replaced an earlier negative-only assertion that a fully blocked WebRTC connection could pass by mistake.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
a Firefox patched at the C++ level driven by stock Playwright. The table above
|
||||
exists because "the proxy isn't working" and "the site is blocking me" get
|
||||
treated as the same sentence far more often than they are the same problem.*
|
||||
@@ -46,7 +46,9 @@ probing for web APIs, and other checks aimed at browser quirks and human behavio
|
||||
family of idea as Hashcash: spend a measurable amount of CPU on something that is
|
||||
cheap for the server to verify. A script that can run arbitrary JavaScript pays this
|
||||
cost the same as a real browser does; a client with no JS engine at all cannot pay it
|
||||
and never produces a token.
|
||||
and never produces a token. A gate built on that idea alone exists in the open, and
|
||||
[Anubis is readable end to end](anubis-proof-of-work-explained.md) in a way Turnstile
|
||||
is not, which makes it the cheapest way to see what this layer can and cannot decide.
|
||||
|
||||
**Proof-of-space** is the storage-based cousin of the same idea, trading disk or
|
||||
memory instead of CPU cycles.
|
||||
@@ -58,7 +60,10 @@ page claims to be. Cloudflare does not publish the exact list of properties it r
|
||||
and the widget script itself is not meant to be human-readable, so anyone claiming a
|
||||
precise inventory of what it checks is going further than Cloudflare's own
|
||||
documentation does. What is documented is the shape of the approach, not the field
|
||||
names.
|
||||
names. The shape is the part worth internalising: a value being wrong matters less
|
||||
than two values disagreeing, which is why a mismatch like
|
||||
[a platform string that contradicts the oscpu beside it](navigator-platform-oscpu-consistency.md)
|
||||
is a stronger signal than either field on its own.
|
||||
|
||||
The point of running all of this before showing anything is stated plainly in
|
||||
Cloudflare's docs too: the goal is to "fine-tune the difficulty of the challenge to
|
||||
@@ -89,7 +94,10 @@ When Managed mode does decide to show something, Cloudflare's own documentation
|
||||
describes it as a "simple checkbox that the visitor must click to proceed", explicitly
|
||||
not an image puzzle or text to transcribe. This is the point worth being precise
|
||||
about: the checkbox is not another fingerprint probe layered on top of the earlier
|
||||
ones. It is a click, gated behind whatever risk score the earlier signals produced.
|
||||
ones. It is a click, gated behind whatever risk score the earlier signals produced,
|
||||
and a click carries its own provenance:
|
||||
[a click dispatched from page JavaScript is never trusted](playwright-clicks-istrusted.md),
|
||||
while one produced by the driver or the engine is.
|
||||
|
||||
That distinction matters for what a real engine can and cannot do about it. Everything
|
||||
in the non-interactive layer, the proof-of-work, the API probing, the consistency
|
||||
|
||||
@@ -59,6 +59,9 @@ need rendering. Each page below states where the other tool covers more.
|
||||
- [Why Playwright Locators Never Throw StaleElementReferenceException](playwright-vs-selenium-stale-element-reference.md) - Selenium's WebElement holds a live reference that goes stale; Playwright's Locator re-resolves on every action.
|
||||
- [How to Read a Stealth-Browser Benchmark Without Being Misled](how-to-read-a-stealth-browser-benchmark.md) - What to check before trusting a comparison, including this project's own, since almost every published one ranks itself first.
|
||||
- [Web Scraping Proxy Costs: Build vs. Buy Your Stealth Stack](web-scraping-proxy-costs-build-vs-buy.md) - Proxy spend, engineering maintenance time and vendor lock-in, without the invented totals most build-vs-buy pages lead with.
|
||||
- [Selenium vs Playwright: the actual differences](difference-between-selenium-and-playwright.md) - Protocol, driver architecture and auto-waiting compared from each project's own docs, plus the one difference neither's docs foreground.
|
||||
- [Alternative Chromium browsers for automation](alternative-chromium-browsers-for-automation.md) - Brave, Edge, Opera, Vivaldi: what actually differs between the forks, and why none of it touches the CDP-level tells that matter.
|
||||
- [Browser automation testing tools, and where each one actually fits](browser-automation-testing-tools.md) - Playwright, Selenium, Cypress, Puppeteer by what they were each built to test, not by feature-list length.
|
||||
|
||||
## Patched-engine, driver-patch and stealth-plugin tools
|
||||
|
||||
|
||||
@@ -20,6 +20,12 @@ widget. The failure is silent in the way CSP failures usually are: no exception
|
||||
Python code, a console warning in the browser you likely never read, and code that
|
||||
simply never ran.
|
||||
|
||||
That is worth reading as a property of the layer, not an accident. An init script is
|
||||
page JavaScript, and page JavaScript is the outermost of
|
||||
[the three levels anything can be changed at](playwright-stealth-levels.md): it is the
|
||||
level the page itself is allowed to have an opinion about, and CSP is the page
|
||||
exercising that opinion.
|
||||
|
||||
## What CSP actually restricts
|
||||
|
||||
By default, a policy that sets `default-src` or `script-src` blocks inline `<script>`
|
||||
@@ -74,7 +80,10 @@ that is a difference from a genuine session, not a neutral convenience. Whether
|
||||
specific target's own logic could ever observe that difference from inside the page is a
|
||||
separate question this page cannot answer for you, but the premise underneath
|
||||
"bypassing CSP is invisible" does not hold: it is a real change to how the page executes,
|
||||
not a transparent workaround.
|
||||
not a transparent workaround. It belongs on the same list as every other setting that
|
||||
makes a session behave unlike a visitor's, which is the list
|
||||
[the checklist for a session being detected](playwright-detected-as-bot.md) works
|
||||
through in order.
|
||||
|
||||
The practical rule: use `bypassCSP` when you are testing your own integration against
|
||||
your own header and you know exactly why it is there. Treat it as a real behavioral
|
||||
|
||||
@@ -56,6 +56,36 @@ useful to a detector: it is stable for one machine, and it varies between
|
||||
machines, because the installed-font set is one of the more distinctive things
|
||||
about a device.
|
||||
|
||||
### The blind spot in that snippet, measured
|
||||
|
||||
The probe above is the one detectors use, and it has a false negative worth knowing
|
||||
before you trust its output: **a family that IS the fallback is invisible to it.**
|
||||
|
||||

|
||||
|
||||
Run that exact function over ten families with `monospace` as the fallback, on Windows,
|
||||
and Consolas comes back **absent**. Consolas is installed. It is also what `monospace`
|
||||
resolves to on that machine, so the candidate width and the baseline width are the same
|
||||
number, and the comparison reads "fell back" when nothing fell back.
|
||||
|
||||
Swap the fallback to `serif` and the same family reads **present**, on the same page in
|
||||
the same session. The invented control family stays absent under both, which is what
|
||||
makes the Consolas row a finding, not a broken probe.
|
||||
|
||||
So the rule stated above holds with one exception: an identical width means the
|
||||
candidate did not render *or* the candidate is the fallback. A detector that probes
|
||||
against a single generic will systematically miss whichever family that generic points
|
||||
at, and which family that is depends on the platform.
|
||||
|
||||
The other thing the three panels show is that the answer does not move. The bundled
|
||||
Firefox headful, the same build headless, and an engine carrying its own font set all
|
||||
return the same ten bits on this host.
|
||||
|
||||
## Why this is different from hashing measureText
|
||||
|
||||
It is easy to lump this in with `measureText` fingerprinting, but the two probe
|
||||
@@ -241,6 +271,12 @@ font set is built from one manifest on every OS, and the width for a run carries
|
||||
single bounded, seed-derived offset instead of the host rasterizer's metrics, so
|
||||
the numbers track the seed rather than the operating system.
|
||||
|
||||
**Why does the probe say a font is missing when I know it is installed?** Because the
|
||||
candidate is the fallback. Measured on Windows: `Consolas` reads absent against a
|
||||
`monospace` fallback and present against a `serif` one, in the same session, since
|
||||
`monospace` resolves to Consolas there and the two widths match. Probe against a second
|
||||
generic before believing an absent.
|
||||
|
||||
## Sources
|
||||
|
||||
- This project's font architecture notes: a bundled Windows font set built from a
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
---
|
||||
title: "Selenium vs Playwright: the differences that matter"
|
||||
description: "Protocol, driver architecture, auto-waiting and browser support from each project's own docs, plus the one difference neither project's docs foregrounds."
|
||||
parent: "Comparisons"
|
||||
nav_order: 39
|
||||
---
|
||||
|
||||
# Selenium vs Playwright: the actual differences
|
||||
|
||||
Both drive a real browser. The differences that matter are in how they talk to
|
||||
it, not in what either one can technically click, and most comparisons stop
|
||||
before the difference that a defended site actually reads.
|
||||
|
||||
## Protocol
|
||||
|
||||
**Selenium** speaks the W3C WebDriver protocol: your test code sends an HTTP
|
||||
request to a driver process (geckodriver, chromedriver), which translates it
|
||||
into browser-specific automation calls. That extra hop is a JSON server in the
|
||||
middle of every action.
|
||||
|
||||
**Playwright** speaks each browser's own remote-debugging protocol directly -
|
||||
CDP for Chromium, its own protocol for Firefox and WebKit - with no
|
||||
intermediate driver process. One fewer moving part, and it is also why
|
||||
Playwright ships its own browser builds rather than driving whatever happens
|
||||
to be installed.
|
||||
|
||||
The practical consequence: Playwright is generally faster and has fewer version
|
||||
mismatches to manage, because there is no separate driver binary to keep in
|
||||
sync with the browser. Selenium's WebDriver layer is a published spec, which
|
||||
is why so many languages and tools speak it; Playwright's protocols are not a
|
||||
public spec, which is why Playwright itself has to ship the client libraries.
|
||||
|
||||
## Auto-waiting
|
||||
|
||||
Selenium waits for an element to exist. Playwright waits for it to be
|
||||
**actionable** - visible, stable, not covered by another element, not
|
||||
disabled - before acting on it. This single design choice removes a large
|
||||
share of the flaky-test problem Selenium suites are known for, where a test
|
||||
clicks an element that technically exists but has not finished animating into
|
||||
place.
|
||||
|
||||
You can build the same waiting logic into a Selenium suite by hand. Playwright
|
||||
builds it into every action by default.
|
||||
|
||||
## Browser support and architecture
|
||||
|
||||
Selenium supports whatever has a WebDriver implementation: Chrome, Firefox,
|
||||
Edge, Safari, and older browsers nobody ships anymore. Playwright supports
|
||||
Chromium, Firefox and WebKit, using patched builds it maintains itself rather
|
||||
than the retail installs on your machine.
|
||||
|
||||
That difference cuts both ways. Selenium can drive the exact browser your users
|
||||
have, retail build and all. Playwright's browsers are a known, pinned,
|
||||
Playwright-maintained artifact - consistent across machines, and also a
|
||||
specific automation build with its own fingerprint, discussed below.
|
||||
|
||||
## Language and ecosystem
|
||||
|
||||
Selenium has bindings older and wider than Playwright's: every mainstream
|
||||
language, decades of Stack Overflow answers, and a WebDriver spec that other
|
||||
tools (Appium, for mobile) build on. Playwright covers JavaScript/TypeScript,
|
||||
Python, Java and .NET officially, younger, with fewer historical workarounds
|
||||
needed because the API was designed after auto-waiting was already a known
|
||||
problem.
|
||||
|
||||
## The difference neither project's own docs foreground
|
||||
|
||||
Both are legitimate testing tools built for testing, and neither one was
|
||||
designed against adversarial detection. But they end up in different places on
|
||||
that axis anyway, for structural reasons:
|
||||
|
||||
**[`navigator.webdriver`](navigator-webdriver-explained.md) is `true` under
|
||||
both by default**, because it is part of the WebDriver spec both implement,
|
||||
not a Selenium-specific flag.
|
||||
|
||||
**Selenium via geckodriver or chromedriver adds an extra network hop and
|
||||
process**, which shows up in timing and in a few CDP/WebDriver-specific
|
||||
properties a determined detector can check for.
|
||||
|
||||
**Playwright's own browser builds [carry properties that differ from a retail
|
||||
install](chromium-is-not-chrome.md)** - build flags, missing OS integration
|
||||
pieces, a UA string that can disagree with what the build actually is -
|
||||
because they were built for automation, not for the browser vendor's own
|
||||
release pipeline.
|
||||
|
||||
Neither framework is "worse" here; both are automation tooling used the way
|
||||
automation tooling looks, which is a separate question from which one has the
|
||||
nicer API.
|
||||
|
||||
**And the layer below both of them is bigger than the gap between them.**
|
||||
Measured in this project on one build, the same seed, changing only the host:
|
||||
font ascent and descent diverged on **58 of 72 families** (up to 27px at 72pt)
|
||||
and line-box height on 61, while **every advance width already matched**,
|
||||
because shaping is the same in-tree library on both. None of that is Selenium
|
||||
or Playwright; it is what the engine and the machine underneath either of them
|
||||
report. Choosing between the two frameworks does not move any of those 58
|
||||
families. This project exists because of that gap:
|
||||
[invisible_playwright](https://github.com/feder-cr/invisible_playwright) is
|
||||
Playwright's own API, unchanged, driving a Firefox patched at the C++ source
|
||||
rather than the stock build - same protocol and auto-waiting Playwright always
|
||||
had, different browser underneath. It does not touch Selenium's side of this
|
||||
at all.
|
||||
[Migrating from Selenium to Playwright for stealth](migrate-selenium-to-playwright-stealth.md)
|
||||
is the practical guide if the browser, not the API, is your actual problem.
|
||||
|
||||
## Which to pick
|
||||
|
||||
- **An existing large Selenium suite, no detection problem:** stay. Rewriting a
|
||||
working suite for architecture purity is rarely worth it.
|
||||
- **A new suite, no detection problem:** Playwright, for auto-waiting alone.
|
||||
- **Automation is being recognized and you need the retail browser exactly as
|
||||
your users have it:** Selenium can drive it directly; Playwright's patched
|
||||
builds are a different thing, unless you point it at a real engine as this
|
||||
project does.
|
||||
- **Automation is being recognized and you can accept a modified engine:**
|
||||
Playwright with a patched build.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Is Playwright faster than Selenium?** Generally yes, from the missing driver
|
||||
hop and less flakiness from auto-waiting, not from any raw execution
|
||||
advantage.
|
||||
|
||||
**Is Playwright replacing Selenium?** For new projects, largely, but Selenium's
|
||||
installed base and WebDriver's status as a real spec keep it relevant,
|
||||
especially where Appium and mobile matter.
|
||||
|
||||
**Does Selenium still get updates?** Yes, actively maintained, including 4.x's
|
||||
own move toward Chrome DevTools Protocol features alongside WebDriver.
|
||||
|
||||
**Which one is more detectable?** Neither is inherently worse; both default to
|
||||
`navigator.webdriver = true` and both are recognizable automation stacks
|
||||
unless something changes the underlying browser.
|
||||
|
||||
**Can I use Playwright's API with Selenium's driver model?** No, they are
|
||||
separate protocols end to end. Patchright and similar projects patch
|
||||
Playwright's own driver instead of switching protocols.
|
||||
|
||||
**See also:**
|
||||
[selenium-driverless vs invisible_playwright](vs-selenium-driverless.md) for the
|
||||
driver-removal approach from Selenium's side, and
|
||||
[Firefox or Chromium for anti-detect automation](firefox-vs-chromium-antidetect.md)
|
||||
for the engine question once you have picked a framework.
|
||||
|
||||
## Sources
|
||||
|
||||
- [Selenium's own documentation on WebDriver and its components](https://www.selenium.dev/documentation/overview/components/), retrieved 2026-09-10.
|
||||
- [Playwright's documentation on browsers and why it ships its own builds](https://playwright.dev/python/docs/browsers), retrieved 2026-09-10.
|
||||
- [MDN, `Navigator.webdriver`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/webdriver) and the [WebDriver specification](https://www.w3.org/TR/webdriver2/#interface), for the flag both frameworks inherit.
|
||||
- This project's own fingerprint gates, for the claim that a patched engine changes what the browser reports versus what Playwright's stock builds report.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
a Firefox patched at the C++ level driven by stock Playwright. This page compares
|
||||
frameworks, not engines - the engine question is a separate page, linked above,
|
||||
because conflating them is the most common mistake in this comparison.*
|
||||
@@ -13,8 +13,11 @@ nav_order: 33
|
||||
failed. Chromium's own network error list defines it as "an operation was aborted
|
||||
(due to user action)," and the cancelling "action" is very often something your own
|
||||
page, your own script, or Playwright's own navigation handling did on purpose. This
|
||||
is the one error on this page's list of siblings that is frequently not a problem at
|
||||
all, and treating every occurrence as a bug wastes time chasing something that
|
||||
is the one error in the `net::ERR_` family that is frequently not a problem at
|
||||
all. [ERR_CONNECTION_RESET](err-connection-reset-playwright.md) and
|
||||
[ERR_HTTP2_PROTOCOL_ERROR](err-http2-protocol-error-playwright.md) report a
|
||||
connection that genuinely broke; this one usually reports one that was closed on
|
||||
purpose, and treating every occurrence as a bug wastes time chasing something that
|
||||
already worked.
|
||||
|
||||
## The causes that are usually fine
|
||||
@@ -61,7 +64,10 @@ in-flight navigation rather than the intended third-party request.
|
||||
**`page.close()` was called while a navigation was still in flight.** Closing the
|
||||
page tears down whatever requests it had open; if that happens mid-navigation on
|
||||
purpose or by an unrelated timeout, the abort is real and the navigation that was
|
||||
racing it never gets a result.
|
||||
racing it never gets a result. When the teardown came from the browser or the
|
||||
context disappearing under you, the exception that surfaces first is usually
|
||||
[TargetClosedError](playwright-targetclosederror-causes.md), and the abort is the
|
||||
second thing you see.
|
||||
|
||||
**A route handler that never resolves.** A `page.route()` interceptor that neither
|
||||
calls `route.continue()`, `route.fulfill()`, nor `route.abort()` leaves a request
|
||||
@@ -92,7 +98,10 @@ of browser realness changes whether it fires. It is a navigation-lifecycle signa
|
||||
that fires identically on a stock Playwright Chromium, a stock Firefox, and this
|
||||
project's patched build, because the cancellation is decided by request-handling
|
||||
logic in the engine, on your own code's instruction, not by anything about how real
|
||||
the browser's identity looks to a remote site.
|
||||
the browser's identity looks to a remote site. The error that does carry that
|
||||
second meaning is a different one:
|
||||
["Execution context was destroyed" can be a navigation you did not ask for](execution-context-destroyed.md),
|
||||
which is worth reading before deciding an abort was a block.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
|
||||
@@ -36,7 +36,10 @@ installed in the browser's trust store, that certificate is signed by an authori
|
||||
nothing trusts. This is functionally identical, from the browser's point of view, to
|
||||
a hostile machine-in-the-middle attack, because it is the same mechanism: someone
|
||||
between you and the destination is terminating TLS you did not expect them to
|
||||
terminate.
|
||||
terminate. Note where in the sequence this leaves you: the tunnel was established
|
||||
and the certificate on the far side of it is what failed. A proxy that refuses the
|
||||
tunnel outright never gets this far and reports
|
||||
[ERR_TUNNEL_CONNECTION_FAILED](err-tunnel-connection-failed-playwright.md) instead.
|
||||
|
||||
**An expired or misconfigured intermediate certificate.** A chain that used to
|
||||
validate can stop validating the moment an intermediate CA cert expires or gets
|
||||
@@ -66,6 +69,14 @@ to be adversarial. A context configured this way cannot tell the difference betw
|
||||
your trusted proxy's re-signed certificate and a hostile one sitting on public
|
||||
Wi-Fi, because the check that would have told them apart is the check you disabled.
|
||||
|
||||
Turning the check off also changes nothing about what the destination sees. A proxy
|
||||
that terminates your TLS and re-establishes its own connection onward presents its
|
||||
own handshake to the server, so the
|
||||
[JA3 and JA4 fingerprint](ja3-ja4-tls-fingerprint.md) arriving at the destination is
|
||||
the proxy's and not your browser's. Whether your browser accepted the proxy's
|
||||
certificate and what the proxy's handshake looks like from the far end are two
|
||||
separate questions, and only the first one is what this error is about.
|
||||
|
||||
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, not every issuer becoming
|
||||
@@ -88,7 +99,11 @@ unexpected interception point produces.
|
||||
interception.
|
||||
3. **Test the same target with the proxy removed.** Validates cleanly without the
|
||||
proxy: the proxy is the one re-signing TLS, confirmed. Still fails: the
|
||||
destination's own certificate is broken, unrelated to the proxy at all.
|
||||
destination's own certificate is broken, unrelated to the proxy at all. A proxy
|
||||
that intercepts TLS is usually also deciding
|
||||
[where your DNS queries go](does-a-proxy-leak-dns-doh-explained.md), which is a
|
||||
separate setting with a separate way of going wrong, and worth reading once while
|
||||
you have the proxy's configuration open.
|
||||
4. **Check with `openssl s_client -connect host:443 -showcerts`** for the full chain
|
||||
and its dates, to rule out an expired intermediate specifically rather than an
|
||||
untrusted one.
|
||||
|
||||
@@ -39,7 +39,10 @@ words, applies to "connections closed with the non-standard code 444," releasing
|
||||
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."
|
||||
rather than a status code that says "blocked." That is the one cause on this list
|
||||
where the error is not a fault to repair but a decision made about your session, and
|
||||
the question then moves off this page and onto
|
||||
[why the script is being refused in the first place](why-does-my-playwright-script-get-blocked.md).
|
||||
|
||||
**A proxy-side rewrite or bypass rule interacting badly with routing.** [A real Playwright
|
||||
report](https://github.com/microsoft/playwright/issues/20703) traces `ERR_EMPTY_RESPONSE`
|
||||
@@ -81,7 +84,12 @@ resemblance to the Chromium string you searched for.
|
||||
that closes with zero bytes, and removes the browser as a variable.
|
||||
2. **Remove the proxy and retry direct.** Gone without it, the proxy or the path to it is
|
||||
implicated, matching the shape in the routing-bypass report above. Persists, the origin
|
||||
server or something between you and it is next.
|
||||
server or something between you and it is next. If the proxy never opened the tunnel
|
||||
at all you would be reading
|
||||
[ERR_TUNNEL_CONNECTION_FAILED](err-tunnel-connection-failed-playwright.md), and if the
|
||||
socket was torn down after some bytes had moved,
|
||||
[ERR_CONNECTION_RESET](err-connection-reset-playwright.md): the three differ only in
|
||||
how far the exchange got.
|
||||
3. **Check whether it is one target or many.** Consistent on one specific site with
|
||||
everything else loading normally is the shape of a deliberate drop; intermittent across
|
||||
unrelated targets points at your own proxy or network path.
|
||||
|
||||
@@ -46,7 +46,10 @@ string while driving Firefox? Look for those two names in your logs instead.
|
||||
- **ALPN disagrees with what actually gets spoken.** HTTP/2 is negotiated in the TLS
|
||||
handshake's ALPN extension. A proxy that terminates TLS and re-negotiates outbound can
|
||||
advertise `h2` to your client while speaking something else to the origin, so the
|
||||
session starts as HTTP/2 and cannot stay one.
|
||||
session starts as HTTP/2 and cannot stay one. A proxy doing that also replaces the
|
||||
handshake the destination sees with its own, so the
|
||||
[JA3 and JA4 fingerprint](ja3-ja4-tls-fingerprint.md) arriving there is the proxy's,
|
||||
which matters separately from whether the session survives.
|
||||
- **A server-side HTTP/2 config problem, unrelated to your proxy.** HTTP/2 enforces
|
||||
header rules HTTP/1.1 never did: no invalid bytes in a header value, a fixed
|
||||
pseudo-header order, framing from RFC 9113 a lenient HTTP/1.1 stack never checked. A
|
||||
@@ -55,11 +58,18 @@ string while driving Firefox? Look for those two names in your logs instead.
|
||||
- **The "error" is not an error.** More than one report traces this exact code to a
|
||||
server sending `RST_STREAM` deliberately, as an anti-automation response rather than a
|
||||
protocol accident. The browser reports both cases identically: a stream closed with
|
||||
`PROTOCOL_ERROR` before delivering anything.
|
||||
`PROTOCOL_ERROR` before delivering anything. If that is what happened, the thing
|
||||
worth reading is not the framing rules but
|
||||
[what an HTTP/2 connection reveals about the client that opened it](http2-fingerprint-detection.md),
|
||||
since the frame order and settings are themselves a fingerprint.
|
||||
|
||||
A smaller set of reports describe the error only in headless mode, disappearing
|
||||
headful, proxy or no proxy. That is in Playwright's own tracker with no confirmed root
|
||||
cause; treat it as something to test for, not an explanation to assume.
|
||||
cause; treat it as something to test for, not an explanation to assume. It is also the
|
||||
one shape on this page where
|
||||
[the separate question of what headless changes](is-playwright-headless-detectable.md)
|
||||
is worth a look, because a mode-dependent failure with no protocol explanation is the
|
||||
signature of something reading the client and not the frames.
|
||||
|
||||
## How to actually find out which one it is
|
||||
|
||||
|
||||
@@ -17,6 +17,10 @@ override from the page, because the page is not where the tell originates.
|
||||
|
||||
## What the driver reveals about itself
|
||||
|
||||
- [What is headless browser automation?](what-is-headless-browser-automation.md) - A real engine with no window, not a lighter fake one. The three properties that differ by default, and why headless-specific detection is mostly a solved category.
|
||||
- [Python browser automation without Selenium](python-browser-automation-without-selenium.md) - Playwright and Pyppeteer, curl_cffi and httpx when you don't need a browser, and how to tell in five minutes whether you need one at all.
|
||||
- [Is Python good for automation?](is-python-good-for-automation.md) - Yes, and the reason is the library ecosystem, not the language. Where it's genuinely strong, where it's a weaker choice.
|
||||
|
||||
- [Can Websites Detect Playwright?](can-websites-detect-playwright.md) - Which webdriver, protocol and fingerprint signals catch a run, and what a patched Firefox fixes.
|
||||
- [Does Playwright Change My Browser Fingerprint?](does-playwright-change-my-fingerprint.md) - Stock Playwright inherits the host's real values instead of randomizing, leaking past a spoofed user agent.
|
||||
- [Does Playwright Get Detected on the First Request?](does-playwright-get-detected-first-request.md) - The TLS handshake and HTTP/2 settings form a network fingerprint detectable before any JavaScript runs.
|
||||
|
||||
@@ -28,6 +28,8 @@ which is exactly why it is worth understanding on its own.
|
||||
|
||||
## Proxy protocols, DNS and IP leaks
|
||||
|
||||
- [How to check a proxy's status before you rely on it](check-proxy-status.md) - Liveness, exit location, latency and browser-level behaviour are four different checks; confusing them misattributes both proxy failures and site blocks.
|
||||
|
||||
- [SOCKS5 vs HTTP proxy: what each does in the browser](socks5-vs-http-proxy-browser.md) - Who authenticates and where: SOCKS auth and DNS in the engine, HTTP auth in the driver.
|
||||
- [Playwright SOCKS5 proxy with authentication](playwright-socks5-proxy-authentication.md) - Why credentials on a socks5:// server fail silently, and the routes that work.
|
||||
- [Does a proxy leak DNS? DoH and DNS leaks explained](does-a-proxy-leak-dns-doh-explained.md) - How a SOCKS5 proxy leaks DNS when the host resolves names locally, and how to verify.
|
||||
|
||||
@@ -219,3 +219,4 @@ for the model that orders the rest, then pick the task you have.
|
||||
- [Automating an Email OTP / Verification-Link Login with Playwright](automating-email-otp-verification-login-playwright.md) - Poll your own inbox over IMAP mid-login and feed the code back into the same session that requested it.
|
||||
- [Automating TOTP-Based 2FA Login with Playwright](automating-totp-2fa-login-playwright.md) - Generate a time-based code with pyotp from the same shared secret an authenticator app would scan; no inbox, no polling.
|
||||
- [How to Scrape a Sandboxed Iframe with Playwright](how-to-scrape-sandboxed-iframe-content-playwright.md) - A `sandbox` attribute can block Playwright's own injected scripts even on a same-origin frame; what the tokens restrict and how to detect it first.
|
||||
- [Puppeteer scraping examples, and what a real defense does to them](puppeteer-scraping-examples.md) - Six standard patterns as code, then run against an actual detector to show what changes and what does not.
|
||||
@@ -39,6 +39,9 @@ telling the difference before you ship a fix, not after.
|
||||
|
||||
## When you get blocked or detected
|
||||
|
||||
- [Selenium detected by Cloudflare](selenium-detected-by-cloudflare.md) - The specific default properties a managed challenge reads, and why patching one from JavaScript does not survive a descriptor check.
|
||||
- [Playwright blocked by CORS policy](playwright-blocked-by-cors-policy.md) - Almost never detection - the browser correctly enforcing a policy the server set. How to tell the two apart.
|
||||
|
||||
- [Playwright detected as a bot on one site: a checklist](playwright-detected-as-bot.md) - a checklist that checks the free fixes first, before buying a better proxy on day one.
|
||||
- [Why Does My Playwright Script Get Blocked?](why-does-my-playwright-script-get-blocked.md) - a four-layer diagnostic across fingerprint, IP reputation, rate and quota, and behaviour.
|
||||
- [Why am I blocked with a clean fingerprint?](why-blocked-with-a-clean-fingerprint.md) - you pass CreepJS, BotD and sannysoft and still get blocked; how to isolate which of four layers is failing.
|
||||
|
||||
@@ -60,6 +60,42 @@ differs will report a different *set* of fonts as installed, even though nothing
|
||||
installed or removed. Two containers from the same image can disagree if their
|
||||
fontconfig caches were built at different times.
|
||||
|
||||
## What this looks like on one Windows machine, measured
|
||||
|
||||

|
||||
|
||||
The three causes above are usually argued from Linux and fontconfig. They show up on
|
||||
Windows too, and the difference is measurable on one machine with nothing installed
|
||||
or removed in between.
|
||||
|
||||
The bench serves a single page from `127.0.0.1` and renders it four times at the same
|
||||
viewport: the bundled Firefox headful and headless, then a patched Firefox headful and
|
||||
headless. Same URL, same host, same session.
|
||||
|
||||
The bundled build disagrees with itself between the two modes on **8,989 of 294,400
|
||||
pixels, or 3.05% of the frame**. The shape of that disagreement is the useful part.
|
||||
Every sample row keeps its exact height, so no glyph got taller. The rows *drift
|
||||
downward* instead, by 0, 1, 1, 2, 2, 2, 2 and 3 pixels from the first sample to the
|
||||
eighth.
|
||||
|
||||
That drift is the mechanism behind a screenshot test that passes on a laptop and fails
|
||||
in CI. Line boxes round to slightly different heights, the error accumulates, and an
|
||||
element halfway down a long page has moved further than one near the top. A tolerance
|
||||
tuned on the first viewport will not hold at the bottom.
|
||||
|
||||
The patched engine returned the same frame in both modes, byte for byte, and did so on
|
||||
three repeats of the whole bench. It declares its own font set instead of reading the
|
||||
host's, so a headless environment has nothing left to be missing.
|
||||
|
||||
One row shows what that costs. `Arial Narrow` is installed on the host, so the bundled
|
||||
build renders it narrow; the patched engine does not carry that face and falls back, so
|
||||
the same row comes out wide. Host independence and host fidelity pull in different
|
||||
directions, and this is where they part.
|
||||
|
||||
## Why any of it matters beyond flaky screenshots
|
||||
|
||||
Fonts are one of the highest-entropy signals a browser exposes, and unlike most of
|
||||
|
||||
@@ -79,6 +79,41 @@ consent iframe loads into the same process as the page and the driver's frame tr
|
||||
reaches it. That is a deliberate trade for a single-purpose automation session, and it
|
||||
is what makes the `frame_locator` pattern below resolve instead of time out.
|
||||
|
||||
## The two workarounds you will find first, and what each one actually does
|
||||
|
||||
Search this problem and the top answers offer two shortcuts before anyone mentions
|
||||
frames. Both are worth understanding, because the reason they fail is the same reason
|
||||
the frame approach works, and one of them fails silently.
|
||||
|
||||
**"Click it with JavaScript."** The suggestion is
|
||||
`page.evaluate("document.querySelector('#accept').click()")`. On a banner that lives in
|
||||
the main document this reaches the button. On a consent banner it usually does not, and
|
||||
for a reason that has nothing to do with Playwright: `evaluate` runs inside the main
|
||||
frame, and the same-origin policy stops any script in that frame from reading into a
|
||||
cross-origin iframe's DOM. `document.querySelector` cannot see the button, so there is
|
||||
nothing to call `.click()` on. This is a browser security rule, not a process-model
|
||||
detail, so it holds whatever isolation strategy the browser runs.
|
||||
|
||||
There is a second cost even where it does reach. A click synthesised from page script
|
||||
carries `isTrusted: false`, which is the one field a handler can check and cannot be
|
||||
assigned from script;
|
||||
[why a JS-dispatched click can never be trusted](playwright-clicks-istrusted.md) is the
|
||||
whole story. A driver-level click does not have that problem, which is what
|
||||
`frame_locator(...).click()` below produces.
|
||||
|
||||
**"Just remove the banner from the DOM."** Deleting the overlay, or hiding it with CSS,
|
||||
removes the thing in front of the content. It does not record a consent decision, and
|
||||
those are different events. Content that the page renders only after consent is stored
|
||||
stays unrendered, so a scrape that looked unblocked returns an empty list; and because
|
||||
nothing was written down, the banner is back on the next run. When the banner is inside
|
||||
an iframe, removing the iframe removes the widget, not the decision.
|
||||
|
||||
The honest exception to both: plenty of sites ship a first-party banner in the main
|
||||
document, no iframe involved. There the JavaScript route does reach the button, and the
|
||||
only remaining question is whether the site's handler cares that the event was not
|
||||
trusted. The iframe case is the one that generates the timeouts people arrive here
|
||||
with.
|
||||
|
||||
## Target the frame, do not force the click
|
||||
|
||||
The correct tool is `frame_locator`. It addresses the iframe first, then finds the
|
||||
@@ -215,6 +250,16 @@ long as it needs to be and no longer.
|
||||
context, yes, so guard the accept with a presence check. With a persistent profile it
|
||||
stays accepted, along with any device permission the flow also stored.
|
||||
|
||||
**Can I just click the accept button with JavaScript?** Usually not on a consent
|
||||
banner. `page.evaluate` runs in the main frame, and the same-origin policy stops any
|
||||
script there from reading into a cross-origin iframe, so `document.querySelector` never
|
||||
finds the button. Where the banner is first-party and in the main document it does
|
||||
reach it, at the cost of an untrusted event.
|
||||
|
||||
**Can I remove the cookie banner instead of accepting it?** You can remove the overlay,
|
||||
but removing it is not consenting. Content the page renders only after a stored consent
|
||||
stays unrendered, and the banner returns next run because nothing was written down.
|
||||
|
||||
## Sources
|
||||
|
||||
- This project's own patch history for the cross-origin iframe root cause, the frame
|
||||
|
||||
@@ -238,7 +238,10 @@ itself the expensive part of the exchange, not the page wrapped around it.
|
||||
Rate limits on WHOIS lookups are tighter than on most catalog pages for exactly
|
||||
that reason, and a pacing scheme copied from a catalog scraper, a random gap
|
||||
of a second or two, will get a lookup service returning empty answers or a
|
||||
captcha well before a similar gap trips a catalog site's limiter.
|
||||
captcha well before a similar gap trips a catalog site's limiter. When the
|
||||
limiter does answer, the response is usually a status code and not a page, and
|
||||
[the backoff that belongs in the middle of a run](how-to-handle-403-429-backoff-mid-scrape-playwright.md)
|
||||
is a different piece of work from the pacing that avoids reaching it.
|
||||
|
||||
```python
|
||||
import random
|
||||
@@ -282,6 +285,12 @@ registry is doing real, expensive work for each one, because it is. The
|
||||
parsing is straightforward once each value is tied to the field that names it;
|
||||
the pacing is what decides whether you get to keep making requests at all.
|
||||
|
||||
One record per domain, with a variable set of labels and a raw block kept
|
||||
alongside, is the shape
|
||||
[JSON Lines handles without a schema argument](how-to-scrape-to-json-lines-playwright.md):
|
||||
a ccTLD that carries three fields and a gTLD that carries twenty go into the
|
||||
same file without either one padding the other.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Does WHOIS only exist as a web page?** No. The original protocol answers in
|
||||
|
||||
@@ -183,6 +183,20 @@ is what this product bundles into the engine on all three platforms, so the same
|
||||
identity reports the same fonts whether the machine underneath is Windows, Linux or a
|
||||
container with nothing installed.
|
||||
|
||||
### What the two browsers report before you change anything
|
||||
|
||||

|
||||
|
||||
Both values differ, and the shape of the difference is the thing to notice. The bundled
|
||||
Firefox headless reports `1366x768`, a laptop resolution it uses whatever viewport you
|
||||
asked for, so every stock headless session on any machine claims the same display. The
|
||||
patched engine reports a declared `1920x1080`.
|
||||
|
||||
Neither browser reports the host's actual monitor, which is the part people expect and
|
||||
do not get.
|
||||
|
||||
## Fix three: the screen and viewport numbers
|
||||
|
||||
A headless browser has no monitor, so every screen value it reports was decided by
|
||||
|
||||
@@ -37,6 +37,13 @@ downstream date is now wrong under the right label. The fix is to match on
|
||||
the label text itself, normalize it through a small alias table, and only then
|
||||
read the adjacent value.
|
||||
|
||||
Check one thing before writing any of it, because it can make the whole section
|
||||
unnecessary: some patent and publication databases ship the same bibliographic
|
||||
fields as machine-readable metadata in the page, and
|
||||
[a JSON-LD block already carries its own labels](how-to-extract-json-ld-structured-data-playwright.md).
|
||||
Where it is present it is the better read, and the selector work below is the
|
||||
fallback for pages that do not have one.
|
||||
|
||||
```python
|
||||
import re
|
||||
from datetime import datetime
|
||||
@@ -256,6 +263,12 @@ the shared invention-level fields once, then attaches jurisdiction-specific
|
||||
fields per member, so a query for "every active family member in this
|
||||
jurisdiction" does not require reconstructing the family from scratch.
|
||||
|
||||
The traversal underneath is the ordinary one:
|
||||
[a list page whose entries each open a detail page](how-to-crawl-list-to-detail-pages-playwright.md),
|
||||
with the wrinkle that here one detail page can expand into several rows. Getting
|
||||
the list-to-detail walk right first makes the family expansion a step you add on
|
||||
top instead of a special case tangled into the crawl.
|
||||
|
||||
```python
|
||||
def scrape_patent_record(url, browser):
|
||||
page = browser.new_page()
|
||||
|
||||
@@ -94,6 +94,12 @@ Store the reading exactly as the feed reported it, with its own timestamp, and s
|
||||
cadence as data rather than assuming it. A downstream consumer that genuinely needs a
|
||||
fixed grid can resample from the as-reported table at query time.
|
||||
|
||||
One row per observation, with whichever variables that station actually reports and no
|
||||
padding for the ones it does not, is the case
|
||||
[JSON Lines was already the right container for](how-to-scrape-to-json-lines-playwright.md):
|
||||
a station reporting three variables and one reporting twenty append to the same file,
|
||||
and a partial run leaves a file that still parses.
|
||||
|
||||
```python
|
||||
def rows_from_feed(feed, variable_map):
|
||||
"""Emit one row per (variable) per observation, using the feed's own timestamps.
|
||||
@@ -199,6 +205,11 @@ list is. It is paginated by day or by month, so a request asks for one calendar
|
||||
and gets back everything that station reported in it. A five-year pull across one
|
||||
station is roughly sixty separate requests, one per month, not one long scroll.
|
||||
|
||||
Sixty requests is long enough that something will interrupt one of them, and a
|
||||
calendar walk has the property that makes recovery cheap: the period is the key, so
|
||||
[a run can pick up from the period it stopped on](how-to-resume-an-interrupted-scrape-playwright.md)
|
||||
without re-reading the years already stored.
|
||||
|
||||
Walk the calendar explicitly and issue one request per period. `page.request` shares
|
||||
the browsing context's cookies with a plain HTTP call, so an archive endpoint gated
|
||||
behind a session the browser already holds answers without a second login flow.
|
||||
|
||||
@@ -88,7 +88,32 @@ But consider what a behavioural check can compare, once you have a curve:
|
||||
So the curve is necessary and not sufficient, which is the same shape as every other
|
||||
part of this subject.
|
||||
|
||||
## How this project does it
|
||||
## The same three layers, measured on one page
|
||||
|
||||

|
||||
|
||||
One page served from `127.0.0.1`, one target, three ways of reaching it. The page draws
|
||||
a dot per `pointermove` and prints the fields it actually received, so the picture and
|
||||
the numbers come from the same run.
|
||||
|
||||
The first thing the panels settle is a negative: **`isTrusted` is `true` in all three,
|
||||
and so `isTrusted` does not separate the driver from the engine.** It only separates
|
||||
both of them from page script. A check that stops at the trusted flag has not
|
||||
distinguished anything here.
|
||||
|
||||
What does separate them is the deltas. The evenly stepped driver path produces **three
|
||||
distinct `movementX` values across 41 events**, because a straight line walked in equal
|
||||
steps reports the same delta almost every time. The engine's path produces **26 distinct
|
||||
values across 34 events**. Same trusted flag, same `pointerType`, same `pressure`, and a
|
||||
completely different distribution underneath.
|
||||
|
||||
And notice what the third panel is not: it is not a graceful arc. The dots stay roughly
|
||||
on the line to the target, clustered at the start and irregular the rest of the way.
|
||||
That is the point of this page in one image. The shape was never the hard part.
|
||||
|
||||
Two pieces, and the split is deliberate.
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 13 KiB |
@@ -78,6 +78,9 @@ The helper API does not change, and that is the point of doing it at this layer.
|
||||
version and from the same seeded profile as everything else. Overriding only that
|
||||
string is the standard way to make a browser contradict itself, and CodeceptJS makes
|
||||
it easy to do by accident because `userAgent` sits right next to the options above.
|
||||
Why one string on its own is the weakest thing to change is
|
||||
[its own subject](is-changing-user-agent-enough.md), and worth reading once before
|
||||
deciding you need the option.
|
||||
|
||||
**One seed per identity, not per run.** A fixed seed makes a failing test
|
||||
reproducible: you can tell the site changing from the browser changing. Rerolling per
|
||||
@@ -95,7 +98,10 @@ The same two things every non-Python route gives up, and you should know them be
|
||||
you pick this layer:
|
||||
|
||||
- **Humanised pointer motion.** The preference enables it, but the paths are drawn
|
||||
by the Python driver from the seed. From CodeceptJS the pointer still teleports.
|
||||
by the Python driver from the seed. From CodeceptJS the pointer still teleports,
|
||||
which matters only against a site that watches behaviour:
|
||||
[what a pointer event carries besides coordinates](human-mouse-movement.md) says
|
||||
which half of that you keep here and which you lose.
|
||||
- **Timezone and locale resolved from the proxy exit.** Those are computed at launch
|
||||
by the Python wrapper. Here you get whatever `prefs.json` was generated with, so a
|
||||
proxy in another country will disagree with the browser unless you regenerate per
|
||||
@@ -111,7 +117,9 @@ Add a scenario that visits a fingerprint page and asserts on the user agent and
|
||||
WebGL renderer. The user agent should say Firefox and the version should match
|
||||
`invisible-playwright version`. If the renderer comes back as a software or basic
|
||||
renderer, either the prefs did not load or the machine has no GPU, and both are worth
|
||||
knowing before the suite reports green.
|
||||
knowing before the suite reports green:
|
||||
[which renderer strings a real machine actually reports](webgl-renderer-strings.md)
|
||||
is the reference for telling one of those two from the other.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
|
||||
@@ -78,7 +78,10 @@ one compiled into the engine and derived from the seed.
|
||||
Two independent opinions do not average out. They disagree, and the disagreement
|
||||
between a generated header set and an engine-level fingerprint is a stronger signal
|
||||
than either being slightly unusual on its own. Turn it off and let one component own
|
||||
the identity.
|
||||
the identity. The reason a disagreement outweighs an oddity is
|
||||
[in what a fingerprint is actually made of](what-is-a-browser-fingerprint.md): it is
|
||||
read as a set of values that have to corroborate each other, not as a list of fields
|
||||
scored one at a time.
|
||||
|
||||
The same argument applies to `userAgent` anywhere in your config: do not set it.
|
||||
|
||||
@@ -89,7 +92,8 @@ and `launchOptions` is typed to accept `launchPersistentContext` parameters too,
|
||||
`userDataDir` belongs there. Pair a stable profile with a stable seed: the profile
|
||||
keeps cookies and storage, the seed keeps the machine those cookies belong to. One
|
||||
without the other is a session whose history and hardware disagree about how long it
|
||||
has existed.
|
||||
has existed. Which number to write down and where to keep it is
|
||||
[the seed's own page](reproducible-agent-browser-identity-seed.md).
|
||||
|
||||
## What this route gives up
|
||||
|
||||
@@ -105,7 +109,9 @@ The same two things every non-Python route gives up:
|
||||
That second point matters more in Crawlee than in most places, because rotating
|
||||
proxies is a normal thing to do here. If your proxy pool spans countries, either
|
||||
generate a `prefs.json` per region and select it per session, or accept that the
|
||||
timezone will be wrong for most of them.
|
||||
timezone will be wrong for most of them, which is
|
||||
[a mismatch a page can check in one line](timezone-proxy-mismatch.md) and not a
|
||||
subtlety anyone has to dig for.
|
||||
|
||||
## Checking it worked
|
||||
|
||||
|
||||
@@ -144,7 +144,10 @@ if __name__ == '__main__':
|
||||
and matching headers, on the assumption that it controls the browser's identity.
|
||||
Here it does not: the identity is compiled into the engine and derived from the
|
||||
seed. Leaving the generator on produces two independent opinions about who this
|
||||
browser is, and the disagreement between them is exactly what detectors read.
|
||||
browser is, and the disagreement between them is exactly what detectors read. It is
|
||||
the same failure a stealth plugin runs into when it patches values on top of an
|
||||
engine that already reports them,
|
||||
[which is the whole subject of the comparison with playwright-extra](vs-playwright-extra-stealth.md).
|
||||
|
||||
**The seed decides whether a failure is debuggable.** With `seed=None` every run is
|
||||
a different machine, so a failing run tells you nothing: you cannot separate the
|
||||
@@ -165,12 +168,17 @@ receives. A SOCKS5 endpoint has to reach `get_default_stealth_prefs` through its
|
||||
engine reads, and it must not also reach Playwright: Playwright configures the
|
||||
proxy itself, without the SOCKS credentials, and that configuration wins over the
|
||||
preferences. HTTP and HTTPS are the other way round and go through Playwright's
|
||||
own `proxy=` argument.
|
||||
own `proxy=` argument. That asymmetry is not a Crawlee quirk:
|
||||
[why SOCKS5 credentials have to arrive as preferences](playwright-socks5-proxy-authentication.md)
|
||||
explains where Playwright drops them, and it applies to every route on this list.
|
||||
|
||||
If you use one, leave locale and timezone on their defaults. They resolve from the
|
||||
exit IP and not from the host machine, which is what keeps the JS timezone, the
|
||||
language list and the IP in agreement. Setting them by hand to your own machine's
|
||||
values is how a session ends up claiming one country while leaving from another.
|
||||
The resolution happens against
|
||||
[a GeoIP database carried locally](offline-geoip-timezone-proxy.md), so it costs no
|
||||
extra request and nothing external learns which exit you are using.
|
||||
|
||||
## When this is the wrong tool
|
||||
|
||||
|
||||
@@ -46,7 +46,9 @@ python -c "import json;from invisible_playwright import get_default_stealth_pref
|
||||
|
||||
Regenerate it when you upgrade the package, since the pref set moves with the engine.
|
||||
Treat `prefs.json` as belonging to a specific seed and a specific version, and keep
|
||||
the seed written down next to it.
|
||||
the seed written down next to it. Which version it belongs to is not a convention
|
||||
either: [the engine is pinned by a seal](pinning.md), and the pairing that file
|
||||
describes is the one you are reproducing by hand here.
|
||||
|
||||
## Step two: launch
|
||||
|
||||
@@ -117,7 +119,9 @@ none of the extra is in the JSON:
|
||||
Python.
|
||||
- **The pin check.** The wrapper refuses to run a binary that does not match the
|
||||
version of the config that produced the prefs. Nothing enforces that pairing here.
|
||||
If you upgrade the binary and keep an old `prefs.json`, nothing will tell you.
|
||||
If you upgrade the binary and keep an old `prefs.json`, nothing will tell you, and
|
||||
the way that goes wrong is quiet: prefs the engine no longer reads simply
|
||||
[do not apply, with no error anywhere](firefox-prefs-not-applying.md).
|
||||
|
||||
So this route is right when the surrounding system is already in Go or Java and
|
||||
rewriting it is not on the table. When the choice is open, Python gets you the parts
|
||||
|
||||
@@ -73,7 +73,9 @@ reproduce a session from.
|
||||
That distinction matters more than it sounds. Sharing one identity across every user
|
||||
of a build is its own signal. If you need a per-session machine, the MCP route is not
|
||||
the one; drive the browser from Python with `InvisiblePlaywright(seed=...)` instead,
|
||||
where the prefs are generated and applied for you.
|
||||
where the prefs are generated and applied for you, or use
|
||||
[an MCP server that launches through the engine](mcp-browser-server-stealth-firefox.md)
|
||||
and therefore has the profile to give.
|
||||
|
||||
## Making the prefs work anyway
|
||||
|
||||
@@ -103,7 +105,9 @@ applies it over the profile's own prefs.
|
||||
|
||||
This is a workaround, not the supported path. It pins one identity for that profile
|
||||
rather than one per session, and the profile keeps cookies and storage between runs,
|
||||
which is either what you wanted or a correlation problem depending on the job.
|
||||
which is either what you wanted or a correlation problem depending on the job. If it
|
||||
is what you wanted, [persistent profiles have their own page](persistent-profiles.md)
|
||||
covering what survives a restart and what does not.
|
||||
|
||||
## Checking it worked
|
||||
|
||||
|
||||
@@ -85,7 +85,9 @@ Open Stealth Browser
|
||||
```
|
||||
|
||||
This has the advantage that the prefs can never drift from the installed package,
|
||||
which is the failure mode a checked-in JSON file eventually produces. The cost is
|
||||
which is the failure mode a checked-in JSON file eventually produces: a stale pref
|
||||
name is not rejected, it is
|
||||
[accepted and then never read](firefox-prefs-not-applying.md). The cost is
|
||||
that `ensure_binary()` may download on the first run of a suite, so a CI job with a
|
||||
short timeout wants the `invisible-playwright fetch` step separately.
|
||||
|
||||
@@ -99,12 +101,14 @@ version and from the same seeded profile as everything else.
|
||||
`colorScheme` are all available there, and each one you set by hand is a value that
|
||||
now has to agree with the profile instead of being derived from it. If you are
|
||||
using a proxy, setting `timezoneId` to your own machine's zone is the classic way to
|
||||
break a session that was otherwise fine.
|
||||
break a session that was otherwise fine, and it breaks it in a way
|
||||
[a page can check against the IP in one line](timezone-proxy-mismatch.md).
|
||||
|
||||
**One seed per identity, not per suite run.** A fixed seed makes a failing test
|
||||
reproducible: you can separate the site changing from the browser changing. If you
|
||||
need several identities in one suite, open several browsers with different seeds
|
||||
rather than rerolling.
|
||||
rather than rerolling. Which surfaces the number actually decides, and which it does
|
||||
not, is [written out on the seed's own page](reproducible-agent-browser-identity-seed.md).
|
||||
|
||||
## What this route gives up
|
||||
|
||||
|
||||
@@ -152,7 +152,10 @@ not per request. It comes from the engine's real version and the seeded profile,
|
||||
overriding only that string is the classic way to make a browser contradict itself.
|
||||
|
||||
**Do not run another stealth layer.** If something else patches `navigator` from
|
||||
inside the page, it is now arguing with an engine that has already answered.
|
||||
inside the page, it is now arguing with an engine that has already answered. The
|
||||
argument is visible from the page, which is why
|
||||
[a patch applied from JavaScript and a value produced by the engine](playwright-stealth-levels.md)
|
||||
are not two ways of doing the same thing.
|
||||
|
||||
**One seed per identity, not per run.** A fixed seed makes a failure reproducible,
|
||||
which is the difference between bisecting a problem and guessing at it. For many
|
||||
@@ -174,6 +177,8 @@ carries are used for an HTTP 407 challenge, and the SOCKS handshake reads its
|
||||
credentials from the proxy prefs, which nothing on that route writes. So on route
|
||||
two an authenticated SOCKS endpoint fails to connect while an unauthenticated one
|
||||
works. Use `http(s)://` there, or take route one.
|
||||
[The full account of where the credentials get dropped](playwright-socks5-proxy-authentication.md)
|
||||
is worth reading before assuming a working proxy is a broken one.
|
||||
|
||||
On route one, leave locale and timezone on `auto` so they follow the exit. On route
|
||||
two they cannot follow anything, which is the main reason to prefer route one when a
|
||||
@@ -183,7 +188,10 @@ proxy is involved at all.
|
||||
|
||||
If the target needs Chromium, use a Chromium backend. If a page does not need
|
||||
JavaScript, plain Scrapy is an order of magnitude faster and no fingerprint is
|
||||
involved at all.
|
||||
involved at all. Reach for this backend when a fingerprint is genuinely in play, and
|
||||
when it is, the order to work through
|
||||
[the layers a block can come from](how-to-scrape-without-getting-blocked.md) decides
|
||||
what to change first, which is rarely the setting people reach for.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
|
||||
@@ -18,6 +18,11 @@ nothing here is a correction of somebody else's page.
|
||||
| TestCafe | yes | **no** | the `path:` browser provider |
|
||||
| Nightwatch | yes | **yes** | `firefox_binary` plus `moz:firefoxOptions.prefs` |
|
||||
|
||||
TestCafe is the one exception in that column, and it is worth reading the row before
|
||||
wiring anything: a route that carries the engine and not the prefs gives you the
|
||||
build's own defaults on every launch, which is a different product from
|
||||
[one identity per session derived from a seed](reproducible-agent-browser-identity-seed.md).
|
||||
|
||||
Get the two values first, the same way for all four:
|
||||
|
||||
```bash
|
||||
@@ -155,7 +160,9 @@ The two things no route outside the Python wrapper carries:
|
||||
For test suites both are usually irrelevant, because a suite normally runs against a
|
||||
known environment and does not need to convince anything. Say so out loud when
|
||||
choosing: the reason to use this engine in a test runner is a realistic rendering and
|
||||
font stack, not evasion.
|
||||
font stack, not evasion. The font stack is the concrete half of that claim, and
|
||||
[what a page can measure about the fonts a machine has](detect-installed-fonts-javascript.md)
|
||||
is where the difference between a real one and a container's default shows up.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
---
|
||||
title: "Is Python good for automation? Yes, and here is why"
|
||||
description: "The reason is the library ecosystem, not the language itself. Where Python is genuinely strong, where it is weaker, and when you actually need a browser."
|
||||
parent: "The Automation Layer"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 49
|
||||
---
|
||||
|
||||
# Is Python good for automation?
|
||||
|
||||
Yes, and it is worth being specific about why, because the honest answer is
|
||||
not "Python the language is elegant" - it is that Python's library ecosystem
|
||||
covers automation's whole range, from a five-line file-renaming script to a
|
||||
browser-driving pipeline, with mature, well-documented tools at every step.
|
||||
|
||||
## Where Python is genuinely strong
|
||||
|
||||
**Readable enough to maintain scripts you write once and touch again in six
|
||||
months.** Automation code has an unusual lifecycle: written quickly, run
|
||||
occasionally, modified rarely. Python's syntax overhead is low enough that a
|
||||
script you wrote in twenty minutes is still legible when you open it again a
|
||||
year later, which matters more for this category of code than for a
|
||||
performance-critical service.
|
||||
|
||||
**A library for nearly every automation surface.** `subprocess` and `os` for
|
||||
system tasks, `schedule` or `APScheduler` for running things on a timer,
|
||||
`requests`/`httpx` for anything HTTP, `pandas` for the data-wrangling step
|
||||
most automation pipelines end with, and Playwright or Selenium when the task
|
||||
needs a real browser. You are rarely writing the hard part from scratch.
|
||||
|
||||
**First-class async support for I/O-bound work.** Automation is frequently
|
||||
I/O-bound - waiting on a network response, waiting on a page to render - and
|
||||
Python's `asyncio` plus async-native libraries (Playwright's async API among
|
||||
them) let you run many such waits concurrently without threads.
|
||||
|
||||
## Where it is a weaker choice
|
||||
|
||||
**Raw CPU-bound speed.** If the automation task itself is computationally
|
||||
heavy (not I/O-bound - actually crunching numbers), Python is slower than
|
||||
compiled languages, and that gap is real. Most browser and file automation is
|
||||
I/O-bound, so this rarely matters in practice, but it is not universally true.
|
||||
|
||||
**Distribution to non-technical end users.** A Python automation script needs
|
||||
a Python environment, or a packaging step (PyInstaller and similar), to reach
|
||||
someone who is not going to run `pip install`. If the deliverable is a
|
||||
double-clickable app for someone else's machine, this is real friction that a
|
||||
compiled or web-based alternative does not have.
|
||||
|
||||
**Concurrency for CPU-heavy parallel work.** The GIL constrains true parallel
|
||||
CPU execution within a single process; for I/O-bound automation this rarely
|
||||
matters (asyncio and threads both work fine), but for CPU-heavy parallel
|
||||
tasks you need multiprocessing, which adds real complexity.
|
||||
|
||||
## What "automation" actually splits into, and what to reach for
|
||||
|
||||
**File and system tasks** - renaming, moving, scheduled jobs, calling other
|
||||
programs: Python's standard library covers this directly, no browser needed.
|
||||
|
||||
**API and data automation** - polling an endpoint, transforming data,
|
||||
writing it somewhere: `requests`/`httpx` plus `pandas`, still no browser.
|
||||
|
||||
**Anything that requires a real browser** - the content only exists after
|
||||
JavaScript runs, or the site has no API: this is where you actually need
|
||||
Playwright or Selenium, and it is worth confirming you are in this category
|
||||
before reaching for a browser, since it is the most expensive tool on this
|
||||
list. `curl` or `requests` against the target URL, checked for whether your
|
||||
data is in the raw response, answers this in under a minute.
|
||||
|
||||
## Getting from "Python is good for this" to a working browser script
|
||||
|
||||
If the task does need a browser, Playwright for Python is the current
|
||||
default recommendation: one async-friendly API, auto-waiting built in, and
|
||||
Chromium, Firefox and WebKit all covered from the same code.
|
||||
|
||||
```python
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch()
|
||||
page = browser.new_page()
|
||||
page.goto("https://example.com")
|
||||
print(page.title())
|
||||
browser.close()
|
||||
```
|
||||
|
||||
That code, unchanged, is also exactly what
|
||||
[invisible_playwright](https://github.com/feder-cr/invisible_playwright) runs
|
||||
underneath - Playwright's own API, with a Firefox patched at the C++ source in
|
||||
place of the [stock automation build](chromium-is-not-chrome.md), for the
|
||||
specific case where the site on the other end is actively checking whether
|
||||
the browser is real.
|
||||
[Python browser automation without Selenium](python-browser-automation-without-selenium.md)
|
||||
covers the framework landscape in more depth if Playwright specifically is not
|
||||
the fit.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**What is Python best used for in automation?** Anything I/O-bound: file and
|
||||
system tasks, API polling, data pipelines, and browser automation, thanks to
|
||||
its library coverage at every layer.
|
||||
|
||||
**Is Python fast enough for automation?** For I/O-bound work, the wait time
|
||||
dominates and Python's own execution speed rarely matters. For CPU-bound
|
||||
work, it is genuinely slower than compiled alternatives.
|
||||
|
||||
**Can Python replace Selenium/Playwright for browser tasks?** Python is the
|
||||
language both frameworks are available in; the question does not apply the
|
||||
other way - you would use Python *with* one of them, not instead of them.
|
||||
|
||||
**Is Python or JavaScript better for browser automation?** Both have
|
||||
first-class Playwright support with equivalent APIs. The better choice is
|
||||
whichever language the rest of your project is already in.
|
||||
|
||||
**Do I need a browser for automation, or is Python's requests library
|
||||
enough?** Check whether your target data exists in the raw HTML response
|
||||
before reaching for a browser - a browser is the more expensive and slower
|
||||
tool and is only necessary when content is JavaScript-rendered.
|
||||
|
||||
**See also:**
|
||||
[Python browser automation without Selenium](python-browser-automation-without-selenium.md),
|
||||
[what is headless browser automation](what-is-headless-browser-automation.md),
|
||||
and [Python web scraping blocked? The TLS fingerprint reason](web-scraping-tls-fingerprint-requests-blocked.md).
|
||||
|
||||
## Sources
|
||||
|
||||
- [Python's own documentation](https://docs.python.org/3/), retrieved 2026-09-10, for the standard-library modules referenced above.
|
||||
- [Playwright for Python documentation](https://playwright.dev/python/docs/intro), retrieved 2026-09-10, for the code example and its browser-coverage claim.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
a Python-and-Playwright project itself. The page tries to answer the question
|
||||
as asked - broadly, about automation in general - before narrowing to the one
|
||||
case this project actually addresses.*
|
||||
@@ -61,6 +61,22 @@ a Firefox user agent painted over it, or a spoofing layer that forgot to delete
|
||||
property that should never have been there. Both expose `navigator.connection` and both
|
||||
get caught by its mere presence.
|
||||
|
||||
## Three absences and one difference
|
||||
|
||||

|
||||
|
||||
`navigator.connection` is `undefined` in both browsers, which is the answer this page
|
||||
gives, and the panel puts two more absences next to it: `navigator.getBattery` and
|
||||
`navigator.userAgentData` are `undefined` too.
|
||||
|
||||
Three absences in a row is the useful shape here. A build that claims Firefox and
|
||||
returns a value for any of the three has contradicted itself, and the contradiction
|
||||
costs a detector one property read. The only line that differs between the two panels
|
||||
is `navigator.webdriver`.
|
||||
|
||||
## Reading it with invisible_playwright
|
||||
|
||||
invisible_playwright is a real Firefox patched at the C++ level and driven by stock
|
||||
|
||||
@@ -95,6 +95,21 @@ An empty or missing `navigator.oscpu` on a browser claiming to be Firefox is the
|
||||
both worlds: absent where Firefox is present, and therefore a tell that the identity is
|
||||
constructed rather than real. Presence with the right value is the only pass.
|
||||
|
||||
### The three, agreeing
|
||||
|
||||

|
||||
|
||||
All three read from one page served from `127.0.0.1`, and the bundled Firefox returned
|
||||
the same three, so the panel shows the agreed state rather than a difference.
|
||||
|
||||
`Win32`, `Windows NT 10.0; Win64; x64` and a user agent naming Windows NT 10.0: three
|
||||
different spellings of one claim. The check in this section is that they keep spelling
|
||||
the same thing, and a screenshot of them agreeing is the baseline the check compares
|
||||
against.
|
||||
|
||||
## Measuring it: read all four and check they agree
|
||||
|
||||
The test is short. Launch, read the four properties, and confirm they tell one story.
|
||||
|
||||
@@ -126,6 +126,21 @@ patched Firefox driven by stock Playwright is Firefox in exactly the way these c
|
||||
test, so it inherits the correct answers without a line of spoofing code and without a
|
||||
getter anyone can catch out of place.
|
||||
|
||||
## The two constants, read from both browsers
|
||||
|
||||

|
||||
|
||||
The two brand constants come back identical from both browsers: `navigator.vendor` is
|
||||
the empty string and `navigator.productSub` is `20100101`, which is what this page says
|
||||
a real Firefox reports.
|
||||
|
||||
That identity is the result, not a missing measurement. The only line that moves in the
|
||||
panel is `navigator.webdriver`, which belongs to a different subject entirely. A tool
|
||||
that had to reshape the two constants would show its work here; nothing had to.
|
||||
|
||||
## Reading them yourself with invisible_playwright
|
||||
|
||||
Do not take the table on faith - read the fields off the browser you actually run, and
|
||||
|
||||
@@ -100,6 +100,20 @@ warm local machine you can lose on a loaded CI box.
|
||||
A value decided inside the engine has no race, because there is no moment before
|
||||
which it was something else.
|
||||
|
||||
## What the two browsers actually return
|
||||
|
||||

|
||||
|
||||
Three values, one page served from `127.0.0.1`, two browsers.
|
||||
|
||||
Only the first line moves. `Function.prototype.toString` called on a native function
|
||||
returns the identical string in both, and `navigator.platform` is `Win32` in both. That
|
||||
is the whole point of the section above: the flag is the easy half, and the two
|
||||
browsers are indistinguishable on the check that usually catches a patched getter.
|
||||
|
||||
## What a real audit checks instead
|
||||
|
||||
A real audit checks a whole fingerprint, not one boolean: descriptor hygiene,
|
||||
|
||||
@@ -16,6 +16,11 @@ cleanup code ever runs. A clean exit never leaks a process, and an exception out
|
||||
killed parent leaks, and the fix cannot live in a `finally` block: it has to be an
|
||||
operating-system job object that Windows tears down when the parent dies.
|
||||
|
||||
Note which direction this is. A leaked process is one the script no longer holds; the
|
||||
opposite case, a script still holding a browser that has gone away, surfaces as
|
||||
[TargetClosedError](playwright-targetclosederror-causes.md), and the two get confused
|
||||
because both start with something dying unexpectedly.
|
||||
|
||||
A bug report said orphaned Firefox processes were piling up on a Windows CI box, and
|
||||
pointed at "any path where teardown doesn't run cleanly - a timeout, an exception out
|
||||
of the `with` block, a killed test runner." That description covers several genuinely
|
||||
@@ -79,7 +84,9 @@ The tempting shortcut - "anything named firefox.exe that showed up after we
|
||||
started" - eventually kills a browser that belongs to a different, healthy,
|
||||
concurrent session, which is a worse failure than leaving one of your own leaked
|
||||
processes running: a leaked process is recoverable, a wrongly-killed one belonging
|
||||
to someone else usually isn't.
|
||||
to someone else usually isn't. That case is not hypothetical the moment you
|
||||
[drive several browsers from one process](run-invisible-playwright-concurrently-asyncio.md),
|
||||
where every one of them answers to the same binary name.
|
||||
|
||||
The actual identification is exact rather than heuristic. Each session generates a
|
||||
random token and stamps it into its own browser's environment at launch; child
|
||||
|
||||
@@ -18,7 +18,7 @@ from invisible_playwright import InvisiblePlaywright
|
||||
with InvisiblePlaywright(
|
||||
seed=42,
|
||||
pin={
|
||||
"gpu.renderer": "ANGLE (NVIDIA, NVIDIA GeForce RTX 4090 Direct3D11)",
|
||||
"gpu.renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)",
|
||||
"gpu.vendor": "Google Inc. (NVIDIA)",
|
||||
"screen.width": 2560,
|
||||
"screen.height": 1440,
|
||||
@@ -32,14 +32,14 @@ with InvisiblePlaywright(
|
||||
|
||||
Pinning a field skips the sampler only for that field - every other field still draws from its own conditional distribution, using the parent's original posterior rather than the value you just pinned. A pinned value does not pull correlated fields along with it.
|
||||
|
||||
The generator is a Bayesian network: every field has a probability distribution **conditioned on its parents**. For example `gpu_class_tier` conditions `screen.tier` and `webgl.msaa_samples`. It does NOT condition `hardware.concurrency`: that one is a root, sampled from the real Windows marginal (`Node("hw_concurrency", parents=[])`), because core count is an OS-level fact rather than a GPU-conditioned one. A high-end GPU will tend to pair with a 2560x1440+ screen; the core count is drawn independently.
|
||||
The generator is a Bayesian network: every field has a probability distribution **conditioned on its parents**. For example `gpu_class_tier` conditions `screen.tier` and the MSAA sample count (drawn, though no longer pinnable or emitted - see below). It does NOT condition `hardware.concurrency`: that one is a root, sampled from the real Windows marginal (`Node("hw_concurrency", parents=[])`), because core count is an OS-level fact rather than a GPU-conditioned one. A high-end GPU will tend to pair with a 2560x1440+ screen; the core count is drawn independently.
|
||||
|
||||
When you pin a field:
|
||||
|
||||
1. The pinned value is written directly, bypassing the sampler.
|
||||
2. **Unpinned children are still sampled from their conditionals** - using the parent's original posterior, not the pinned value.
|
||||
|
||||
That last point is the subtle one: pinning breaks the conditional chain. If you pin `gpu.renderer` to an RTX 4090 string but leave `screen` unpinned, the sampler will pick `screen` from the seed-derived tier (which might be `low_end`), producing a physically implausible "RTX 4090 + 1366x768" pairing.
|
||||
That last point is the subtle one, and `gpu.*` is the exception to it: a GPU pin selects a whole persona, so the class of the persona you picked conditions the screen, concurrency and storage still being drawn (see the `gpu.*` section below). Where an implausible pairing can still be built is by pinning both halves, because a value you write explicitly is never re-drawn: put a `low_end` persona next to `screen.width: 3840, screen.height: 2160` and you get exactly that, on a tier that draws a 4K screen zero times in 200 seeds.
|
||||
|
||||
**Rule of thumb:** pin correlated fields together, or just trust the sampler.
|
||||
|
||||
@@ -51,27 +51,62 @@ Keys are dotted paths. All values are optional - omitted keys fall back to the s
|
||||
|
||||
| Key | Type | Example | Notes |
|
||||
|-----|------|---------|-------|
|
||||
| `gpu.class_tier` | str | `"high_end"` | The **root** of the Bayesian network. One of `"low_end"`, `"mid_range"`, `"high_end"`, `"integrated_old"`, `"integrated_modern"`. Pin this alone to steer the whole profile (screen, concurrency, MSAA, ...) toward a coherent tier without having to name each sub-field. |
|
||||
| `gpu.vendor` | str | `"Google Inc. (NVIDIA)"` | Must exactly match the renderer vendor prefix, otherwise detectors catch the mismatch. |
|
||||
| `gpu.renderer` | str | `"ANGLE (NVIDIA, NVIDIA GeForce RTX 4090 Direct3D11)"` | Windows ANGLE string. Used by WebGL's [`UNMASKED_RENDERER_WEBGL`](https://developer.mozilla.org/en-US/docs/Web/API/WEBGL_debug_renderer_info). |
|
||||
| `gpu.class_tier` | str | `"mid_range"` | Selects a persona of that class. Only classes the validated pool actually contains can be pinned; anything else raises. |
|
||||
| `gpu.vendor` | str | `"Google Inc. (NVIDIA)"` | Selects a persona by vendor. Combined with `gpu.renderer` both must match the same persona. |
|
||||
| `gpu.renderer` | str | see below | Selects a persona by its Windows ANGLE string, the one WebGL reports as [`UNMASKED_RENDERER_WEBGL`](https://developer.mozilla.org/en-US/docs/Web/API/WEBGL_debug_renderer_info). |
|
||||
|
||||
**Why `class_tier` is pinnable separately from `renderer`.** They live at different levels of abstraction:
|
||||
**A GPU pin SELECTS a persona, it does not set a string.** This is the one place
|
||||
in this table where you are not free to invent a value, and the reason is that
|
||||
the renderer string does not travel alone. Around 81 `getParameter` values, the
|
||||
shader-precision formats and the whole extension list belong to the same GPU, and
|
||||
a detector cross-checks the name against them - a name over another card's
|
||||
parameters is the mismatch that scores ~0.70 on a commercial checker. So the
|
||||
engine ships a pool of validated personas, each one a complete and coherent set,
|
||||
and a pin picks one of them.
|
||||
|
||||
- `class_tier` is a **coarse handle** over the whole Bayesian graph. It gates the distribution of `screen`, `webgl.msaa_samples`, and [storage quota](hardware-concurrency-device-memory.md). Pin `{"gpu.class_tier": "low_end"}` and the sampler returns a *coherent* low-end machine - small screen, 4x MSAA - without you having to specify each field.
|
||||
- `renderer` is an **exact string** that lands verbatim in WebGL's `UNMASKED_RENDERER_WEBGL`. Useful when you want to imitate a specific GPU the target site has seen before. Does **not** condition other fields - if you pin `renderer` to an RTX 4090 but leave `class_tier` unpinned, `class_tier` is re-sampled from scratch and might disagree with the renderer string (see [How sampling + pinning interact](#how-sampling--pinning-interact)).
|
||||
Two consequences:
|
||||
|
||||
In practice most users should pin `class_tier` alone, or pin `renderer`+`vendor`+`class_tier` together if they want full control.
|
||||
- **A renderer, vendor or class the pool cannot present is REFUSED**, with a
|
||||
`ValueError` that names the values that are available. It is not silently
|
||||
ignored. Up to 2026-09-15 it was: a pin for an RTX 4090 set the label on the
|
||||
profile object and left the browser reporting the seed's own GPU, so
|
||||
`InvisiblePlaywright(pin={"gpu.renderer": ...})` returned a profile that
|
||||
disagreed with the page. Do not hard-code the valid strings from this page -
|
||||
read them off the exception, which is generated from the pool itself.
|
||||
- **A GPU pin conditions the rest of the profile.** Screen, concurrency, MSAA and
|
||||
[storage quota](hardware-concurrency-device-memory.md) are re-sampled around
|
||||
the pinned persona's class, so you cannot end up with a low-end GPU behind
|
||||
high-end storage. You do not need to pin `class_tier` alongside `renderer`;
|
||||
pinning `class_tier` alone is still the coarse handle, it just picks the
|
||||
persona too.
|
||||
|
||||
### `screen.*`
|
||||
|
||||
`screen.avail_width` and `screen.avail_height` left this table on 2026-09-15
|
||||
for the same reason as the tier: the engine derives the available rect from
|
||||
`width`, `height` and `taskbar_px`, and none of the three avail values is
|
||||
emitted, so pinning one moved a label on the profile and nothing a page can
|
||||
read. Pin `screen.width`, `screen.height` and `screen.taskbar_px`; availWidth
|
||||
and availHeight follow from them, which is what keeps two properties of one
|
||||
window from disagreeing.
|
||||
|
||||
`screen.tier` was in this table until the same day and is not a knob: pins are
|
||||
applied after the sampler has drawn, so pinning the tier could not condition the
|
||||
screen it names, and it emitted no preference. It is the sampler's own label for
|
||||
the screen it chose, and it is still on the profile as one. Pin `screen.width`
|
||||
and `screen.height` to choose a screen.
|
||||
|
||||
`codec.webspeech_synth` left the table the same day, and left the profile with
|
||||
it. `media.webspeech.synth.enabled` is emitted as a constant `true`, which is
|
||||
what retail Firefox does on desktop; the sampled field only ever made the
|
||||
profile disagree with the browser, on about 12% of seeds.
|
||||
|
||||
|
||||
| Key | Type | Example |
|
||||
|-----|------|---------|
|
||||
| `screen.width` | int | `2560` |
|
||||
| `screen.height` | int | `1440` |
|
||||
| `screen.avail_width` | int | `2560` |
|
||||
| `screen.avail_height` | int | `1400` |
|
||||
| `screen.dpr` | float | `1.0`, `1.25`, `1.5`, `2.0` |
|
||||
| `screen.tier` | str | `"1080p"`, `"1440p"`, `"4k"`, ... |
|
||||
| `screen.color_depth` | int | `24` | `screen.colorDepth` and `screen.pixelDepth`. Declared rather than read off the panel: the engine only returned a fixed 24 when resistFingerprinting was on, which we do not turn on because it is itself a tell, so before this it reported the real display - 30 on a wide-gamut monitor, and a persona claiming an office laptop with a 30-bit panel is a contradiction a page can read. |
|
||||
|
||||
### `hardware.*`
|
||||
@@ -108,13 +143,16 @@ In practice most users should pin `class_tier` alone, or pin `renderer`+`vendor`
|
||||
| `codec.webm_encoder_enabled` | `MediaRecorder` advertises WebM support. |
|
||||
| `codec.mediasource_webm` | `MediaSource.isTypeSupported('video/webm')`. |
|
||||
| `codec.mediasource_mp4` | `MediaSource.isTypeSupported('video/mp4')`. |
|
||||
| `codec.webspeech_synth` | `speechSynthesis.getVoices()` returns a fabricated voice list. |
|
||||
|
||||
### `webgl.*`
|
||||
### `webgl.*` - retired
|
||||
|
||||
| Key | Type | Example | Notes |
|
||||
|-----|------|---------|-------|
|
||||
| `webgl.msaa_samples` | int | `4`, `8`, `16` | `MAX_SAMPLES` WebGL parameter. Conditioned on `gpu.class_tier` when sampled. |
|
||||
There is no pinnable `webgl.*` key. `webgl.msaa_samples` was one until 2026-09-15,
|
||||
and pinning it did nothing on Windows: the emitted sample count is held at 4 so
|
||||
`gl.SAMPLES` is constant across sessions, because a varying count changes the
|
||||
WebGL parameters hash even when the renderer does not. Honouring the pin on Linux
|
||||
alone is what made the two builds emit different counts for the same seed - seven
|
||||
of eight measured seeds. Both emit 4 now, so a pin has nothing left to move, and
|
||||
the key refuses rather than looking like it worked.
|
||||
|
||||
### `font.*`
|
||||
|
||||
@@ -188,7 +226,7 @@ Pin the whole visible tuple - GPU, screen, concurrency, audio:
|
||||
```python
|
||||
pin = {
|
||||
"gpu.vendor": "Google Inc. (Intel)",
|
||||
"gpu.renderer": "ANGLE (Intel, Intel(R) Iris(R) Xe Graphics Direct3D11)",
|
||||
"gpu.renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)",
|
||||
"gpu.class_tier": "mid_range",
|
||||
"screen.width": 1920,
|
||||
"screen.height": 1080,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
---
|
||||
title: "Playwright blocked by CORS policy: not bot detection"
|
||||
description: "The browser enforcing a policy the server set, identically for a human tab. How to tell it apart from a real block, and three legitimate ways past it."
|
||||
parent: "Testing and Troubleshooting"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 31
|
||||
---
|
||||
|
||||
# Playwright blocked by CORS policy
|
||||
|
||||
A request fails with something like "has been blocked by CORS policy: No
|
||||
'Access-Control-Allow-Origin' header is present." This is worth stating
|
||||
plainly first: **this is not bot detection.** It is the browser correctly
|
||||
enforcing a same-origin policy that exists for every browser, automated or
|
||||
not, and Playwright is doing exactly what a real browser does here.
|
||||
|
||||
## What is actually happening
|
||||
|
||||
CORS (Cross-Origin Resource Sharing) is a server-controlled permission system.
|
||||
When JavaScript running on `page-a.com` tries to fetch a resource from
|
||||
`api-b.com`, the browser sends the request and then checks whether
|
||||
`api-b.com`'s response includes headers that explicitly permit that origin. If
|
||||
the headers are absent or do not list your origin, the browser withholds the
|
||||
response from your script - even though the request often already succeeded on
|
||||
the wire.
|
||||
|
||||
This applies identically in a real human's Chrome tab and in a Playwright
|
||||
script. It is not a signal the server is using to detect automation; it is a
|
||||
security boundary the browser enforces regardless of who or what is driving it.
|
||||
|
||||
## How to tell it apart from a real block
|
||||
|
||||
**Check the network tab (or `page.on("response")`).** If the request itself
|
||||
returns a normal status code and body, and the failure is purely a script-side
|
||||
CORS error, that confirms it: the server answered fine, the browser withheld
|
||||
the response from your JavaScript. That is CORS, not detection.
|
||||
|
||||
**If the request itself never completes, or returns 403/429/a challenge page,**
|
||||
that is a different problem - the server refused the request outright, which
|
||||
is a detection or rate-limit question, not a CORS one.
|
||||
[Why does my Playwright script get blocked](why-does-my-playwright-script-get-blocked.md)
|
||||
covers that case.
|
||||
|
||||
## The three legitimate ways past a real CORS restriction
|
||||
|
||||
**Do not fetch it from page-context JavaScript at all.** Playwright can make
|
||||
the request directly from Node/Python via [`page.request`](how-to-capture-xhr-api-responses-playwright.md)
|
||||
or an API request context, which is not subject to the browser's CORS
|
||||
enforcement because it is not a page-originated `fetch()` call. If you just need the data and not a
|
||||
page-side reaction to it, this is usually the simplest fix and it is not a
|
||||
workaround - it is a legitimate use of Playwright's API-testing surface.
|
||||
|
||||
**Navigate to the resource's own origin.** If `api-b.com` serves a page you
|
||||
can load directly, do the interaction there instead of cross-origin from
|
||||
`page-a.com`.
|
||||
|
||||
**Check whether the API actually wants to be called this way.** A CORS
|
||||
restriction is often the API owner saying "call this from your server, not
|
||||
from a browser tab." If there is a documented server-to-server endpoint,
|
||||
that is the intended path, and Playwright's `page.request` context or a plain
|
||||
HTTP client outside the browser context are both appropriate ways to use it.
|
||||
|
||||
## What this project does and does not touch
|
||||
|
||||
CORS enforcement lives in the browser engine and is unrelated to fingerprinting
|
||||
or detection countermeasures. Nothing about running a patched, stealth-tuned
|
||||
Firefox changes CORS behaviour, and nothing here proposes bypassing it - the
|
||||
same-origin policy is a real security boundary, not a bot-detection heuristic,
|
||||
and defeating it from a page you do not control is a different and much more
|
||||
serious thing than working around a fingerprint check.
|
||||
|
||||
If what led here is actually a fingerprint or automation-detection problem
|
||||
that happens to surface alongside a CORS-looking error - a
|
||||
[Content-Security-Policy block](content-security-policy-blocks-playwright-scripts.md)
|
||||
reads similarly in the console - separate the two first using the network-tab
|
||||
check above before assuming either one is the cause of the other.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Does Playwright trigger CORS errors that a real browser would not?** No.
|
||||
Playwright's browsers enforce the same CORS policy any browser does. If a
|
||||
human hitting the same cross-origin request in their own browser would also
|
||||
be blocked, Playwright blocking it is not a Playwright-specific issue.
|
||||
|
||||
**Can I disable CORS in Playwright?** You can launch Chromium with
|
||||
`--disable-web-security` for local testing, which is a real footgun outside a
|
||||
throwaway test context and does not apply to Firefox. It changes the
|
||||
browser's own enforcement, not what the target server permits, and using it
|
||||
against a real third-party site is not something this project recommends.
|
||||
|
||||
**Is a CORS error the same as being blocked by anti-bot protection?** No.
|
||||
Confirm which one you have with the network-tab check above before treating it
|
||||
as a detection problem.
|
||||
|
||||
**Why does the same request work in curl but not in Playwright?** Because
|
||||
curl is not a browser and is not subject to CORS at all - it is a browser-only
|
||||
enforcement mechanism. That is also why `page.request` in Playwright, which
|
||||
does not run in page context, does not hit it either.
|
||||
|
||||
**Will a proxy fix a CORS error?** No. CORS is about the origin your script
|
||||
runs in, not the network path the request takes.
|
||||
|
||||
**See also:**
|
||||
[Why does my Playwright script get blocked?](why-does-my-playwright-script-get-blocked.md),
|
||||
[Content-Security-Policy blocks Playwright scripts](content-security-policy-blocks-playwright-scripts.md),
|
||||
and [how to capture XHR/API responses with Playwright](how-to-capture-xhr-api-responses-playwright.md)
|
||||
for the `page.request` approach applied to real scraping.
|
||||
|
||||
## Sources
|
||||
|
||||
- [MDN, Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS), retrieved 2026-09-10, for the mechanism described above.
|
||||
- [Playwright's documentation on API testing and request contexts](https://playwright.dev/python/docs/api-testing), retrieved 2026-09-10, for the `page.request` path that is not subject to page-context CORS.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright).
|
||||
This page exists to say plainly that a CORS error is not what this project
|
||||
addresses, and to point at the actual fix rather than let it be mistaken for a
|
||||
fingerprint problem.*
|
||||
@@ -52,7 +52,11 @@ hit-testing still applies, and whatever sits on top at that point is what
|
||||
receives it. You have not reached your element; you have clicked the overlay
|
||||
blind. Whatever handler fires belongs to the obstruction - or to nothing -
|
||||
while your script carries on believing the button was pressed, which is how a
|
||||
forced click turns one visible failure into a silent wrong path.
|
||||
forced click turns one visible failure into a silent wrong path. The hit test is
|
||||
the same one that
|
||||
[consumed most of the humanised pointer path on the calls real scripts make](hover-mouse-movement-bug.md),
|
||||
which is worth knowing because it means the check is doing real work and not
|
||||
merely being cautious.
|
||||
|
||||
Second, and this is the part worth internalizing instead of skipping past:
|
||||
clicking blind into an overlay is itself a tell, on any
|
||||
@@ -78,7 +82,10 @@ except Exception:
|
||||
```
|
||||
|
||||
**2. Check if it is timing rather than layout.** If the obstruction is a transition or an
|
||||
animation, waiting for it to finish is the actual fix, not forcing through it:
|
||||
animation, waiting for it to finish is the actual fix, not forcing through it. A
|
||||
transition that removes and rebuilds the element instead of moving it produces
|
||||
[the not-attached error rather than this one](playwright-element-not-attached-to-dom.md),
|
||||
so which of the two you get already narrows what the page is doing:
|
||||
|
||||
```python
|
||||
locator = page.get_by_role("button", name="Submit")
|
||||
|
||||
@@ -39,6 +39,11 @@ binary, and it is not there because that command never ran on this machine.
|
||||
**How to confirm it:** check whether `playwright install` appears anywhere in your setup
|
||||
script, Dockerfile, or CI workflow. If it does not, that is the fix, full stop.
|
||||
|
||||
This project splits the same way and for the same reason, with its own command for the
|
||||
step: [the engine is fetched separately from the package](installation.md), so a fresh
|
||||
environment that installed one and not the other lands on this error from the other
|
||||
direction.
|
||||
|
||||
## Cause 2: a Docker or cross-platform build produced binaries for the wrong OS
|
||||
|
||||
A subtler variant: the install step did run, but it ran on a different operating system
|
||||
@@ -53,6 +58,10 @@ the expected path is simply not there in a runnable form for this OS.
|
||||
Dockerfile or CI job that later launches the browser, not assuming a cache
|
||||
copied in from elsewhere is compatible. Playwright's official images run this step
|
||||
during the image build specifically so the browsers match the container's own platform.
|
||||
Once it launches, a container introduces a second and unrelated set of problems that
|
||||
have nothing to do with paths:
|
||||
[what an image is missing that a desktop has](how-to-use-invisible-playwright-in-docker.md)
|
||||
is the next thing to read, not this page.
|
||||
|
||||
## Cause 3: missing system dependencies, which is a different error wearing the same clothes
|
||||
|
||||
|
||||
@@ -98,6 +98,21 @@ the engine gives itself away in a dozen other places the header cannot reach. If
|
||||
genuinely need a mobile browser, the honest answer is a WebKit or Chromium context, not a
|
||||
Firefox one dressed up as a phone.
|
||||
|
||||
### The screen the two browsers report
|
||||
|
||||

|
||||
|
||||
Two values, one page served from `127.0.0.1`. The screen differs and the device pixel
|
||||
ratio does not: both report `1`.
|
||||
|
||||
That is the section's argument in two rows. The screen is decided below the client, so
|
||||
it changes when the engine changes, while `devicePixelRatio` stayed at `1` in both
|
||||
because neither run asked for anything else. A mobile preset that sets a ratio on the
|
||||
client cannot move the first number, and the two have to agree for the identity to hold
|
||||
together.
|
||||
|
||||
## The engine owns the screen size, not the client
|
||||
|
||||
The screen size on a Firefox context belongs to the seeded engine, not to whatever a
|
||||
|
||||
@@ -139,6 +139,31 @@ keep doing that for those reasons. Choose between them on isolation, not on
|
||||
whether the fingerprint comes out right, because now it comes out right either
|
||||
way.
|
||||
|
||||
## The two calls, side by side, today
|
||||
|
||||

|
||||
|
||||
One page served from `127.0.0.1`, three sessions, headless throughout.
|
||||
|
||||
The first panel is the default this page is about, still there: `browser.new_page()` on
|
||||
the bundled Firefox reports **1280x720** on a screen it claims is 1366x768. The second
|
||||
panel is the same build asked for a context with no viewport, and the inner size becomes
|
||||
1366x683, which is a window on that screen rather than a number from a config file.
|
||||
|
||||
The first panel also carries a second, quieter contradiction, and it is the kind this
|
||||
page is really about: `outerHeight` reads **805** while `availHeight` reads **720**. The
|
||||
window is taller than the space the operating system says is available. No maximised
|
||||
window on a real desktop does that.
|
||||
|
||||
The third panel is the check on our side, which is the part we owe you rather than
|
||||
Playwright: `browser.new_page()` on the patched engine reports 1920x947, the same
|
||||
numbers its own `new_context` produces. The convenience call no longer picks up a
|
||||
default nobody chose.
|
||||
|
||||
## How to check your own setup for the same shape of bug
|
||||
|
||||
Whatever tool you use, the check is the same three lines and it takes a session,
|
||||
|
||||
@@ -81,10 +81,15 @@ recommended" for exactly this case, because a positional pick is fragile: it is
|
||||
only as long as the page's element order does not change, and nothing announces when it
|
||||
does. Reordering a list, adding a new row above the one you meant, or a responsive layout
|
||||
that renders elements in a different sequence on a smaller viewport all silently break a
|
||||
`.first()` that happened to work.
|
||||
`.first()` that happened to work. A list that rebuilds itself between the pick and the
|
||||
click produces
|
||||
[the not-attached error instead](playwright-element-not-attached-to-dom.md), which is
|
||||
the same fragility arriving as a different message.
|
||||
|
||||
**`{force: true}` or `strict_selectors=False`.** Neither narrows the match; both just
|
||||
suppress the check. `strict_selectors=False` in particular reproduces the exact failure
|
||||
suppress the check, and `force` has
|
||||
[its own way of going wrong on a click that is merely covered](playwright-element-click-intercepted.md):
|
||||
it delivers the click at the coordinates regardless of what is on top of them. `strict_selectors=False` in particular reproduces the exact failure
|
||||
mode strict mode was built to prevent: Playwright picks one of the matches for you, and
|
||||
which one it picks is not something the error message ever told you to verify. If the
|
||||
count is ever wrong again after the page changes, nothing will tell you.
|
||||
|
||||
@@ -24,6 +24,20 @@ This page covers what the string has to agree with, why rotation makes things wo
|
||||
rather than better, the Client Hints trap in Chromium, the one case where setting it is
|
||||
correct, and what to do instead.
|
||||
|
||||
### The three strings, read from a real session
|
||||
|
||||

|
||||
|
||||
The three strings that have to agree, read from one page served from `127.0.0.1`. The
|
||||
bundled Firefox returned the same three, so this panel is a reference rather than a
|
||||
comparison: it is what agreement looks like when nobody has touched anything.
|
||||
|
||||
Change only the first line and the other two keep saying Windows in their own words.
|
||||
That is why the rotation advice in the next section is what it is.
|
||||
|
||||
## What the user agent has to agree with
|
||||
|
||||
**Changing `navigator.userAgent` does not touch roughly eight other signals a page can
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
---
|
||||
title: "Puppeteer scraping examples, and what a real defense does"
|
||||
description: "Six standard patterns as code, then what happens against a real detector: the patterns are fine, the browser underneath them is what actually gets read."
|
||||
parent: "Scraping with Playwright"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 170
|
||||
---
|
||||
|
||||
# Puppeteer scraping examples, and what happens when you run them against a real defense
|
||||
|
||||
Every Puppeteer tutorial shows the same six patterns. They are worth having in
|
||||
one place, and worth being honest about: none of them, run as written, holds
|
||||
up against a site that is actively checking for automation. This page shows
|
||||
the patterns, then shows what a real check does to them.
|
||||
|
||||
## The six standard patterns
|
||||
|
||||
**Basic extraction.**
|
||||
|
||||
```js
|
||||
const browser = await puppeteer.launch();
|
||||
const page = await browser.newPage();
|
||||
await page.goto('https://example.com');
|
||||
const title = await page.$eval('h1', el => el.textContent);
|
||||
await browser.close();
|
||||
```
|
||||
|
||||
**Waiting for dynamic content.**
|
||||
|
||||
```js
|
||||
await page.goto('https://example.com/listings');
|
||||
await page.waitForSelector('.listing-card');
|
||||
const items = await page.$$eval('.listing-card', cards =>
|
||||
cards.map(c => c.querySelector('.title')?.textContent)
|
||||
);
|
||||
```
|
||||
|
||||
**Pagination.**
|
||||
|
||||
```js
|
||||
let allItems = [];
|
||||
while (true) {
|
||||
const items = await page.$$eval('.item', els => els.map(e => e.textContent));
|
||||
allItems = allItems.concat(items);
|
||||
const next = await page.$('.next-page:not(.disabled)');
|
||||
if (!next) break;
|
||||
await next.click();
|
||||
await page.waitForNetworkIdle();
|
||||
}
|
||||
```
|
||||
|
||||
**Screenshots for debugging or archival.**
|
||||
|
||||
```js
|
||||
await page.screenshot({ path: 'page.png', fullPage: true });
|
||||
```
|
||||
|
||||
**Filling and submitting a form.**
|
||||
|
||||
```js
|
||||
await page.type('#search-input', 'query text');
|
||||
await page.click('#search-button');
|
||||
await page.waitForNavigation();
|
||||
```
|
||||
|
||||
**Intercepting network requests to read API responses directly.**
|
||||
|
||||
```js
|
||||
page.on('response', async (response) => {
|
||||
if (response.url().includes('/api/items')) {
|
||||
const data = await response.json();
|
||||
console.log(data);
|
||||
}
|
||||
});
|
||||
await page.goto('https://example.com');
|
||||
```
|
||||
|
||||
## What a real check does to all six
|
||||
|
||||
Run any of the above against `bot.sannysoft.com` or a similar public detector,
|
||||
and the pattern itself is not what fails - the *browser underneath* it is.
|
||||
Every one of these scripts launches Puppeteer's default bundled Chromium,
|
||||
which:
|
||||
|
||||
- Sets `navigator.webdriver` under the CDP automation layer Puppeteer speaks.
|
||||
- Ships as a specific, versioned automation build distinguishable from a
|
||||
retail Chrome install on request.
|
||||
- Produces a WebGL/canvas fingerprint tied to whatever GPU (or lack of one) the
|
||||
host machine has, unrelated to the code pattern used.
|
||||
|
||||
None of the six patterns above caused any of that. The `$eval`, the
|
||||
`waitForSelector`, the pagination loop - all correct, idiomatic Puppeteer.
|
||||
The tells live one layer down, in what browser Puppeteer launched and how it
|
||||
is being driven - the same [CDP-visible](bidi-vs-cdp-detection.md) automation
|
||||
layer, not in which selector method you called.
|
||||
|
||||
## The two fixes, and where each one lives
|
||||
|
||||
**Fix the pattern-level mistakes first, because they are real.** A fixed
|
||||
`waitForTimeout(2000)` instead of `waitForSelector` produces flaky, slow
|
||||
scrapes that themselves look unusual in aggregate. Skipping
|
||||
`waitForNetworkIdle()` before reading paginated content produces truncated
|
||||
results that have nothing to do with detection. These are worth fixing
|
||||
regardless of any anti-bot concern.
|
||||
|
||||
**Fix the browser identity separately, because the code above cannot touch
|
||||
it.** If the site is specifically checking automation signals, no amount of
|
||||
selector correctness changes `navigator.webdriver`, the CDP fingerprint, or
|
||||
the build identity. That is a browser-engine question, not a scraping-pattern
|
||||
question, and it needs a different browser underneath the same code:
|
||||
[Patchright](vs-patchright.md) for a patched Chromium driver on
|
||||
Puppeteer/Playwright's Chrome side, or this project's patched Firefox if you
|
||||
can move off Chromium entirely.
|
||||
[Migrating from Puppeteer to Playwright for stealth](migrate-puppeteer-to-playwright-stealth.md)
|
||||
is the practical path from the code above toward that fix, keeping the same
|
||||
scraping logic and changing only the engine underneath it.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Why does my working Puppeteer script get blocked on some sites and not
|
||||
others?** The sites that block it are checking automation-layer signals your
|
||||
scraping logic does not touch. Sites that do not check simply never notice.
|
||||
|
||||
**Is Puppeteer detectable by default?** Yes, in the sense that its default
|
||||
bundled Chromium reports as an automated build under inspection, the same way
|
||||
any framework's default browser does.
|
||||
|
||||
**Do I need Puppeteer-extra-plugin-stealth?** It patches several of the same
|
||||
known Chrome-side tells that Patchright addresses at the driver level; check
|
||||
its current maintenance status before depending on it for anything important,
|
||||
since stealth plugins of this shape tend to lag behind detector updates.
|
||||
|
||||
**Can these examples be adapted to Playwright directly?** Yes - the concepts
|
||||
(`waitForSelector`, request interception, pagination loops) map closely, and
|
||||
Playwright's own auto-waiting removes the need for some of the explicit waits
|
||||
shown above.
|
||||
|
||||
**Will intercepting API responses avoid detection better than reading the
|
||||
DOM?** It avoids some rendering-related overhead and can be faster, but it is
|
||||
still the same browser and the same automation layer making the request - it
|
||||
does not change what the browser reports about itself.
|
||||
|
||||
**See also:**
|
||||
[Migrating from Puppeteer to Playwright for stealth](migrate-puppeteer-to-playwright-stealth.md),
|
||||
[puppeteer-real-browser vs invisible_playwright](vs-puppeteer-real-browser.md),
|
||||
and [how to capture XHR/API responses with Playwright](how-to-capture-xhr-api-responses-playwright.md)
|
||||
for the request-interception pattern done in Playwright's API.
|
||||
|
||||
## Sources
|
||||
|
||||
- [Puppeteer's own API documentation](https://pptr.dev/), retrieved 2026-09-10, for the methods used in the examples above.
|
||||
- This project's own detector gates, for the claim that browser-layer signals, not scraping-pattern code, are what a real check reads first.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright).
|
||||
The code on this page is ordinary Puppeteer, shown honestly next to what it
|
||||
does and does not survive, rather than presented as a stealth technique it
|
||||
never was.*
|
||||
@@ -0,0 +1,134 @@
|
||||
---
|
||||
title: "Python browser automation without Selenium: the options"
|
||||
description: "Playwright and Pyppeteer, or no browser at all when the data is in the HTML. What leaving Selenium buys you, and what it does not change all by itself."
|
||||
parent: "The Automation Layer"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 48
|
||||
---
|
||||
|
||||
# Python browser automation without Selenium
|
||||
|
||||
Selenium is the default answer people reach for, and it is often not the
|
||||
right one for a new project. This page is the actual landscape: what replaces
|
||||
it, what each option buys you, and - the question worth asking first - whether
|
||||
you need a browser at all.
|
||||
|
||||
## Ask this first: do you need a browser?
|
||||
|
||||
If the data you want is present in the page's initial HTML response - view
|
||||
source and search for it - you do not need a browser. `requests` or `httpx`
|
||||
fetches the page in milliseconds with no rendering overhead. If the site does
|
||||
heavy anti-bot fingerprinting at the TLS/HTTP layer even for a plain request,
|
||||
`curl_cffi` reproduces a real browser's TLS handshake shape from Python
|
||||
without launching one.
|
||||
|
||||
If the content only appears after JavaScript runs - infinite scroll, a
|
||||
React/Vue app, content loaded via a later fetch call - then yes, you need a
|
||||
real browser engine, and the rest of this page is for you. If the block is
|
||||
specifically at the TLS/HTTP handshake layer rather than in the rendered
|
||||
content, [curl_cffi](vs-curl-cffi.md) is the narrower fix, covered further
|
||||
down.
|
||||
|
||||
## The Python options, without Selenium
|
||||
|
||||
**Playwright for Python.** The most complete modern option: auto-waiting
|
||||
built in, first-class async support, and one API across Chromium, Firefox and
|
||||
WebKit. Microsoft maintains it, and it ships its own browser builds rather
|
||||
than driving whatever is installed on the machine. This is the framework most
|
||||
new Python browser-automation projects should default to.
|
||||
|
||||
**Pyppeteer.** A Python port of Puppeteer, driving Chromium over CDP directly
|
||||
with no separate driver process, similar in spirit to how Playwright talks to
|
||||
Chromium. It has a smaller community than Playwright and historically lags
|
||||
behind Puppeteer's own releases, which is worth weighing before committing to
|
||||
it for a long-lived project.
|
||||
|
||||
**Requests-HTML** and similar lightweight wrappers exist but are largely
|
||||
unmaintained at this point and add a thin, dated layer over an embedded
|
||||
Chromium; for anything beyond a quick script, either of the two above is a
|
||||
better foundation.
|
||||
|
||||
## What you gain by leaving Selenium specifically
|
||||
|
||||
**No separate driver process.** Selenium talks to geckodriver or chromedriver
|
||||
over the [W3C WebDriver](navigator-webdriver-explained.md) HTTP protocol -
|
||||
Playwright and Pyppeteer talk to the browser's own protocol directly, which is
|
||||
faster and has one fewer moving part to keep version-matched with the
|
||||
browser.
|
||||
|
||||
**Auto-waiting by default.** Selenium waits for an element to exist in the
|
||||
DOM; Playwright waits for it to be actionable - visible, stable, not covered,
|
||||
enabled - before acting, which removes a large share of the flaky-test
|
||||
problem Selenium code is known for. [Selenium vs Playwright: the actual
|
||||
differences](difference-between-selenium-and-playwright.md) has the full
|
||||
comparison if that is the deciding factor for you.
|
||||
|
||||
**What does not change automatically.** Neither Playwright nor Pyppeteer is
|
||||
inherently less detectable than Selenium out of the box. Both set
|
||||
`navigator.webdriver` under their respective automation protocols, both ship
|
||||
recognizable automation-build browsers by default, and both are subject to
|
||||
the same class of TLS/driver-level tells Selenium has. Switching frameworks
|
||||
for code-quality reasons is a good move on its own merits; switching
|
||||
frameworks *expecting it to solve a detection problem* usually does not,
|
||||
because the underlying browser identity is the thing that has to change, not
|
||||
the API wrapped around it.
|
||||
|
||||
## If detection is the actual reason you are leaving Selenium
|
||||
|
||||
Then the framework was never the real lever. What moves the needle is the
|
||||
browser build underneath, however you drive it:
|
||||
|
||||
- **On Chromium**, Patchright patches Playwright's own Chromium driver to
|
||||
remove the CDP-level and WebDriver-level tells at the source rather than
|
||||
papering over them from JavaScript.
|
||||
- **On Firefox**, this project - [invisible_playwright](https://github.com/feder-cr/invisible_playwright) -
|
||||
is the same idea taken further: a Firefox patched at the C++ source, with
|
||||
Playwright's own unmodified API on top, so the code you write is standard
|
||||
Playwright and the browser underneath is not a stock automation build.
|
||||
|
||||
Both approaches keep Selenium out of the picture entirely and address the
|
||||
actual layer where the tells live.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**What replaces Selenium in Python?** Playwright, for most new projects.
|
||||
Pyppeteer if you specifically want a Puppeteer-equivalent API and are
|
||||
comfortable with a smaller, slower-moving community.
|
||||
|
||||
**Do I need a headless browser for web scraping in Python?** Only if the data
|
||||
you need is not present in the raw HTML response. Check with `curl` or
|
||||
`requests` first; a browser is the more expensive tool and should be reached
|
||||
for when it is actually necessary.
|
||||
|
||||
**Is Playwright faster than Selenium?** Generally yes, mostly from removing
|
||||
the separate driver process and from Playwright's own auto-waiting reducing
|
||||
retries.
|
||||
|
||||
**Is curl_cffi a replacement for a browser?** No, it replaces the need for a
|
||||
browser specifically when the block is at the TLS/HTTP fingerprint layer and
|
||||
the content does not require JavaScript execution.
|
||||
|
||||
**Will switching from Selenium to Playwright stop me getting blocked?** Not
|
||||
by itself. Both default to a recognizable automation build; the browser
|
||||
identity is the layer that needs to change, separate from which framework
|
||||
drives it.
|
||||
|
||||
**See also:**
|
||||
[Selenium vs Playwright: the actual differences](difference-between-selenium-and-playwright.md),
|
||||
[Migrating from Selenium to Playwright for stealth](migrate-selenium-to-playwright-stealth.md),
|
||||
and [Python web scraping blocked? The TLS fingerprint reason](web-scraping-tls-fingerprint-requests-blocked.md)
|
||||
for when you do not need a browser at all.
|
||||
|
||||
## Sources
|
||||
|
||||
- [Playwright for Python documentation](https://playwright.dev/python/docs/intro), retrieved 2026-09-10, for the API and browser-management model.
|
||||
- [Pyppeteer's own repository](https://github.com/pyppeteer/pyppeteer), retrieved 2026-09-10, for its maintenance status and scope relative to upstream Puppeteer.
|
||||
- [curl_cffi's own documentation](https://github.com/lexiforest/curl_cffi), retrieved 2026-09-10, for TLS-fingerprint impersonation without a browser engine.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
a Firefox patched at the C++ level driven by stock Playwright. The framework
|
||||
question and the browser-identity question are kept separate on purpose,
|
||||
because most "I switched frameworks and I'm still blocked" reports are the
|
||||
second question wearing the first one's name.*
|
||||
@@ -77,7 +77,9 @@ with InvisiblePlaywright(seed=42) as browser:
|
||||
|
||||
This is the difference between debugging a failure and guessing at one: same seed,
|
||||
same browser, so a failing run can be replayed exactly rather than hoping the next
|
||||
random draw reproduces it.
|
||||
random draw reproduces it. The seed reaches the browser layer and stops there, and
|
||||
[what it does not pin](reproducible-agent-browser-identity-seed.md) is the half worth
|
||||
reading before treating a stable fingerprint as a finished job.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
|
||||
@@ -56,6 +56,25 @@ the interesting shape: it does not ask a single question, it asks two and compar
|
||||
answers. That pattern, cross-checking two sources that must agree, is what everything
|
||||
modern is built on.
|
||||
|
||||
## The same properties, read from both browsers
|
||||
|
||||

|
||||
|
||||
Seven of the values this page describes, read from one page served from `127.0.0.1`,
|
||||
first by Playwright's bundled Firefox and then by a patched engine. Three of the seven
|
||||
differ.
|
||||
|
||||
The three that move are the three the table is really testing: `navigator.webdriver`
|
||||
goes from `true` to `false`, the plugin count from `0` to `5`, and the screen from
|
||||
`1366x768` to `1920x1080`. The four that do not move matter as much, because they show
|
||||
what this page is arguing: `Notification.permission`, the user agent, the colour depth
|
||||
and `navigator.platform` are already the same in both, so a row that agrees is not
|
||||
evidence of anything either way.
|
||||
|
||||
## Group two: the property dump
|
||||
|
||||
The long list below the table is not pass/fail. It prints values:
|
||||
|
||||
@@ -50,6 +50,39 @@ The related traps:
|
||||
the numbers differ from Windows and should match whatever platform you claim.
|
||||
- A machine claiming Windows with a macOS-shaped available area is a contradiction.
|
||||
|
||||
## What the numbers actually are, on one machine
|
||||
|
||||

|
||||
|
||||
Before applying the check above, it is worth knowing what it returns today. One
|
||||
Windows machine, one page served from `127.0.0.1`, three headless sessions shown, and a
|
||||
headful one measured alongside them but not printed here, because a headful window
|
||||
reports the display of whichever machine it ran on.
|
||||
|
||||
**The taskbar check does not fire on this browser.** Playwright's bundled Firefox,
|
||||
headless, reports `1366x768` with `availHeight` of `720`: a 48 pixel gap, and the
|
||||
headful session measured beside it reported the same 48. So `availHeight === height` is
|
||||
a real class of tell and this particular browser is not an example of it. Test the
|
||||
browser you actually run rather than inheriting the example.
|
||||
|
||||
**What is a tell here is that the screen is a constant.** The first two panels are the
|
||||
same build at viewports of 430x200 and 1000x700, and the display stays `1366x768`
|
||||
through both. It is not derived from anything you asked for, and it is the same laptop
|
||||
resolution in every stock headless session. A detector does not need the taskbar
|
||||
comparison when the value itself never moves.
|
||||
|
||||
One sharp edge worth stating, because it is ours: with the patched engine, **an
|
||||
explicit `viewport` leaves `outerWidth` reporting the declared window while
|
||||
`innerWidth` follows what you asked for.** Measured at viewport 430x200 the pair reads
|
||||
1920x1032 against 430x200, which is 1490 pixels of browser chrome and no real window
|
||||
looks like that. With `no_viewport=True`, the panel above, the same pair reads 1920x1032
|
||||
against 1920x947, an 85 pixel difference that is an ordinary tab strip and address bar.
|
||||
If the identity matters more than the exact page size, do not pin the viewport.
|
||||
|
||||
## The relationships that have to hold
|
||||
|
||||
**The viewport cannot be bigger than the screen.** `innerWidth` greater than
|
||||
@@ -156,6 +189,11 @@ platform, held stable for the identity. Rarity is the problem, not the specific
|
||||
platform. It is also the value people most often set to 1 for convenience, on a
|
||||
resolution where 1 is implausible.
|
||||
|
||||
**What screen size does Playwright's Firefox report in headless mode?** `1366x768`, with
|
||||
`availHeight` at `720`. Measured at two different viewports on the same machine and it
|
||||
did not move either time, so it is a constant rather than something derived from your
|
||||
session, and it is the same laptop resolution in every stock headless run.
|
||||
|
||||
## Sources
|
||||
|
||||
- [MDN: `Screen.availHeight`](https://developer.mozilla.org/en-US/docs/Web/API/Screen/availHeight),
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
---
|
||||
title: "Selenium detected by Cloudflare: the defaults that fail"
|
||||
description: "The specific properties a managed challenge reads that Selenium leaves at their defaults, and why a JavaScript override of one of them stays checkable."
|
||||
parent: "Testing and Troubleshooting"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 30
|
||||
---
|
||||
|
||||
# Selenium detected by Cloudflare
|
||||
|
||||
A Selenium session hitting a Cloudflare-managed challenge - the interstitial,
|
||||
or a Turnstile widget that never resolves - is one of the most common reports
|
||||
in browser automation, and it has a specific, well-documented cause rather than
|
||||
a mysterious one.
|
||||
|
||||
## What Cloudflare is actually reading
|
||||
|
||||
A managed challenge scores the session from several layers before anything you
|
||||
did on the page is relevant:
|
||||
|
||||
- **The network path** - address type and reputation.
|
||||
- **The TLS/HTTP handshake shape** - properties that differ between an
|
||||
automated client and a real browser's network stack.
|
||||
- **What the browser reports about itself** - and this is where Selenium's
|
||||
defaults are specifically weak.
|
||||
|
||||
## Where Selenium's defaults fail this test
|
||||
|
||||
**[`navigator.webdriver`](navigator-webdriver-explained.md) is `true`.**
|
||||
Selenium implements the W3C WebDriver spec, and that flag exists in the spec
|
||||
precisely to announce automation. It is set by default in every unmodified
|
||||
Selenium session, in every browser Selenium drives.
|
||||
|
||||
**geckodriver/chromedriver add an observable layer.** The separate driver
|
||||
process that Selenium talks to over WebDriver's HTTP+JSON protocol introduces
|
||||
[CDP-visible](bidi-vs-cdp-detection.md) and WebDriver-visible properties that a
|
||||
stock retail browser session never produces, because a retail browser is
|
||||
never being driven by an external process at all.
|
||||
|
||||
**Default launch flags are recognizable.** `--enable-automation` and similar
|
||||
flags were historically set by default in automated Chrome sessions and are
|
||||
directly checkable. Firefox under Selenium sets its own automation-related
|
||||
preferences the same way.
|
||||
|
||||
**No history, no cookies, a fresh profile every run.** Separate from the
|
||||
protocol-level tells: a session with zero browsing history behind it is itself
|
||||
a signal a scoring system can weigh, independent of anything WebDriver-specific.
|
||||
|
||||
**And one host-derived value can flip a verdict on its own.** Measured in this
|
||||
project with A/B/A on a single build: the CSS system-font keywords a page can
|
||||
read came from the host's UI settings rather than from the browser's declared
|
||||
identity, so a browser announcing Windows reported `Segoe UI` at 12px on
|
||||
Windows and `Sans` at 13.3333px on Linux. Setting it to `Segoe UI` gave
|
||||
`tampering=False, suspect=4, anomaly=0`; putting it back to `Sans` gave
|
||||
`True/12/1`; setting it again gave `False/4/0`. One value, both directions,
|
||||
same build. It is worth knowing before you attribute a challenge to Selenium
|
||||
specifically: a scoring system reads whatever disagrees with itself, and the
|
||||
disagreement is often the machine rather than the driver.
|
||||
|
||||
## Why patching one property at a time does not work
|
||||
|
||||
The common first fix is a JavaScript injection that overrides
|
||||
`navigator.webdriver` to return `false`. This addresses exactly one of the
|
||||
signals above and does two things wrong at once: it leaves the CDP-level and
|
||||
driver-process-level tells untouched, and the override itself is detectable,
|
||||
because a property that is normally a native getter now shows up with a
|
||||
JavaScript-defined one if a script checks `Object.getOwnPropertyDescriptor`
|
||||
or the function's own `toString()`.
|
||||
|
||||
A managed challenge that scores dozens of signals is not defeated by
|
||||
patching one property from the page after the fact. The properties need to be
|
||||
correct at the source - the browser build and the driver - not overridden
|
||||
after the browser already exists.
|
||||
|
||||
## What actually changes the outcome
|
||||
|
||||
**Warm the session first.** A profile with real history and cookies, from a
|
||||
prior real session, is a stronger signal than any single property fix.
|
||||
`--user-data-dir` pointed at a persistent profile is the mechanism; it does
|
||||
not remove the WebDriver flag, but it removes the "session with zero history"
|
||||
signal.
|
||||
|
||||
**Address and pacing, before the browser.** If the request originates from a
|
||||
datacenter address or arrives in an inhuman rhythm, no browser-side change
|
||||
matters. This is usually the larger share of the score.
|
||||
|
||||
**A driver that does not announce itself.** [Patchright](vs-patchright.md)
|
||||
removes the Chromium-side WebDriver and CDP-level tells at the driver layer
|
||||
rather than patching properties from JavaScript, which is the correct place
|
||||
to fix a protocol-level signal. On the Firefox side, this project does the same thing
|
||||
architecturally: the properties Cloudflare checks are set correctly inside the
|
||||
patched engine itself, not injected after the browser launches, which is why
|
||||
they survive a `toString()` or descriptor check that a JavaScript override
|
||||
does not.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Does Selenium set navigator.webdriver to true?** Yes, by default, because it
|
||||
is part of the W3C WebDriver spec Selenium implements.
|
||||
|
||||
**Can I just override navigator.webdriver with JavaScript?** You can, and it
|
||||
fixes one property while leaving the CDP/driver-level and behavioural signals
|
||||
untouched, and the override itself is checkable.
|
||||
|
||||
**Does using undetected-chromedriver fix this for Selenium?** It addresses
|
||||
several of the same-family Chrome-side tells specifically. It does not touch
|
||||
Firefox, and it does not change address or pacing signals.
|
||||
|
||||
**Will a proxy fix a Cloudflare challenge on Selenium?** If the address was
|
||||
the trigger, often. If the trigger is the WebDriver flag or driver-level
|
||||
signals, a proxy changes none of that.
|
||||
|
||||
**Is there a Selenium option that removes the automation flag?** Selenium
|
||||
itself does not remove the WebDriver-mandated flag; that would mean not
|
||||
implementing the spec it exists to implement. The fix lives at the driver or
|
||||
engine layer, not in Selenium's own API surface.
|
||||
|
||||
**See also:**
|
||||
[Migrating from Selenium to Playwright for stealth](migrate-selenium-to-playwright-stealth.md),
|
||||
[selenium-stealth: is it still maintained](selenium-stealth-unmaintained.md),
|
||||
and [what navigator.webdriver really tells a site](navigator-webdriver-explained.md)
|
||||
for the flag's full mechanism.
|
||||
|
||||
## Sources
|
||||
|
||||
- [MDN, `Navigator.webdriver`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/webdriver) and the [WebDriver specification](https://www.w3.org/TR/webdriver2/#interface), retrieved 2026-09-10, for the flag's spec-mandated behaviour under Selenium.
|
||||
- [Selenium's own documentation](https://www.selenium.dev/documentation/), retrieved 2026-09-10, for the driver-process architecture described above.
|
||||
- Cloudflare's public documentation on managed challenges, for what a challenge scores beyond a single JavaScript property.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
a Firefox patched at the C++ level driven by stock Playwright, not Selenium. The
|
||||
architectural argument here - fix it at the engine, not with a JavaScript patch
|
||||
- is the same rule this project follows for its own patches.*
|
||||
@@ -35,7 +35,9 @@ bounded, tested, working exactly as configured.
|
||||
|
||||
That's the trap. A timeout on each request answers "how long do I wait for this one
|
||||
server to respond." It says nothing about "how long am I willing to wait for the step
|
||||
as a whole to finish." With three endpoints in the list and a ten-second timeout on
|
||||
as a whole to finish." What a launch resolves from the network is the reason the
|
||||
delay lands there and not on a page load, and part of it is
|
||||
[deriving the timezone and locale from the proxy's exit](offline-geoip-timezone-proxy.md). With three endpoints in the list and a ten-second timeout on
|
||||
each, the worst case was three sequential ten-second waits plus connection overhead -
|
||||
correctly bounded per-request, and entirely unbounded as a caller-facing guarantee.
|
||||
Every piece was well-behaved. Their sum was not something anyone had actually put a
|
||||
|
||||
@@ -45,6 +45,20 @@ anomaly, checkable the same way.
|
||||
are altering values inside the exact runtime the opponent's code is also running in, and
|
||||
the opponent always gets to look at what you changed.
|
||||
|
||||
## The one value that moves, and the one that does not
|
||||
|
||||

|
||||
|
||||
Two values, read from one page served from `127.0.0.1`.
|
||||
|
||||
`navigator.webdriver` moves. `Function.prototype.toString` on a native function returns
|
||||
the identical string from both browsers, which is the comparison that matters when the
|
||||
fix is an init script: a patched getter has to survive being asked what it is, and a
|
||||
value decided inside the engine is never asked.
|
||||
|
||||
## What it never touches, by construction
|
||||
|
||||
An init script cannot change what the font subsystem enumerates, what the GPU driver
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
---
|
||||
title: "What is headless browser automation, and what differs"
|
||||
description: "A real browser with no window, not a lighter fake one. The three properties that differ by default, and why headless-specific detection mostly closed."
|
||||
parent: "The Automation Layer"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 47
|
||||
---
|
||||
|
||||
# What is headless browser automation?
|
||||
|
||||
Headless browser automation is running a real browser engine - the same layout,
|
||||
JavaScript and rendering code as the normal browser - with no window drawn to a
|
||||
screen. It is not a simulation and not a stripped-down substitute; it is the
|
||||
identical engine, started with a flag that tells it not to open a visible
|
||||
window.
|
||||
|
||||
## What it is for
|
||||
|
||||
**Servers with no display.** A CI runner or a container has no screen, so a
|
||||
browser that insists on painting one is a non-starter. Headless is the default
|
||||
mode for browser-based testing in CI for exactly this reason.
|
||||
|
||||
**Speed and resource use.** Not painting pixels to a screen saves work, and
|
||||
headless instances typically use less memory and start faster, which matters
|
||||
when you are running hundreds of them in parallel.
|
||||
|
||||
**Scale.** Ten browsers with windows compete for screen space that does not
|
||||
exist on a server anyway. Ten headless instances are ten processes, nothing
|
||||
more.
|
||||
|
||||
## What it is not for
|
||||
|
||||
Headless is not a way to make a browser less real. Every layout calculation,
|
||||
every JavaScript execution, every network request happens exactly as it does
|
||||
headed. If your problem is that a page's content depends on visual rendering
|
||||
you can inspect by eye, headless removes the eye, not the rendering.
|
||||
|
||||
## The three properties that differ by default
|
||||
|
||||
This is the part most explanations skip, and it is why "headless vs headful"
|
||||
became its own detection category rather than a footnote.
|
||||
|
||||
**`navigator.webdriver`.** Set to `true` under most automation setups regardless
|
||||
of headless or headed, because it reflects the WebDriver protocol being used,
|
||||
not the display mode. Conflating this with headless specifically is a common
|
||||
mistake.
|
||||
|
||||
**Window and screen dimensions.** A headless launch without an explicit
|
||||
viewport historically reported unusual or default dimensions that a headed
|
||||
browser on a real display would not, and older headless-Chrome builds
|
||||
identified themselves in the user-agent string outright (`HeadlessChrome`).
|
||||
Modern headless modes have closed the most obvious version of this, but
|
||||
viewport and screen mismatches remain a real signal if you do not set them
|
||||
deliberately.
|
||||
|
||||
**GPU and rendering behaviour.** A server headless launch commonly has no real
|
||||
GPU behind it, so [WebGL and canvas output](canvas-fingerprint-changes-every-run.md)
|
||||
can differ from what a desktop with a graphics card produces - not because it
|
||||
is headless, but because the machine underneath has no GPU. This is a machine
|
||||
fact that headless mode exposes rather than causes.
|
||||
|
||||
How large that machine effect is, measured in this project rather than
|
||||
estimated: rendering the same text across **48 family/size/weight
|
||||
combinations**, the same build produced **9 to 19 distinct alpha levels per
|
||||
render on Windows and 193 to 256 on Linux**, with 16 of the 48 cases using all
|
||||
256. Same browser, same code, same display mode. The variable was the host's
|
||||
rasterizer, and no headless flag touches it. That is the shape of the problem
|
||||
people are usually looking at when they blame headless: a machine difference
|
||||
wearing the display mode's name.
|
||||
|
||||
## Why headless-specific detection is mostly a solved category
|
||||
|
||||
A few years ago, headless Chrome was trivially fingerprintable: a distinct
|
||||
user-agent substring, missing browser plugins that a real Chrome always
|
||||
reported, and inconsistent `Notification.permission` behaviour were enough on
|
||||
their own. Chrome's modern headless mode (the "new headless", the default
|
||||
since Chrome 112) closed the most obvious ones, and Firefox's headless mode was
|
||||
never as separable in the first place because it reuses more of the same code
|
||||
path.
|
||||
|
||||
What is left is not "is this headless" but the underlying machine and driving
|
||||
signals: no GPU, a container font list, the WebDriver flag, and how the
|
||||
automation drives input. Those exist headed or headless. Running headed on a
|
||||
machine that has a display available removes one variable for free and costs
|
||||
nothing; it does not make an otherwise-scripted, WebDriver-flagged, container-fonted
|
||||
session pass as human.
|
||||
|
||||
## What actually changes the outcome
|
||||
|
||||
- **Set viewport and screen dimensions explicitly**, rather than accepting
|
||||
whatever the launch default is.
|
||||
- **Run headed when you have a real display and no CI constraint**, since it is
|
||||
free and removes one class of headless-specific signal.
|
||||
- **Do not treat headless-vs-headed as the fix for a detection problem
|
||||
elsewhere.** If the machine has no GPU, a container font set and an IP with a
|
||||
datacenter reputation, switching to headed changes none of that.
|
||||
- **If the site is checking WebDriver-protocol flags or the automation build's
|
||||
own tells**, that is the driver and the browser, not the display mode.
|
||||
[What navigator.webdriver really tells a site](navigator-webdriver-explained.md)
|
||||
covers the flag; this project addresses the browser build itself.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Is headless Chrome still detectable?** The obvious markers from the old
|
||||
headless mode are largely closed in the new one. What remains is GPU absence,
|
||||
font set and driving-protocol signals, which are machine and driver facts, not
|
||||
display-mode facts.
|
||||
|
||||
**Does running headed avoid bot detection?** No on its own. It removes one
|
||||
narrow signal class and leaves the IP, the machine and the automation flags
|
||||
unchanged.
|
||||
|
||||
**What is the difference between headless and headful?** Whether a window is
|
||||
drawn. The rendering engine underneath is identical.
|
||||
|
||||
**Why does my headless browser fail a fingerprint test that my headed one
|
||||
passes?** Usually the machine, not the mode: no GPU changes WebGL and canvas
|
||||
output regardless of display mode, and a server without a display is often a
|
||||
container without a GPU too.
|
||||
|
||||
**Can a headless browser pass as a real user?** For anything that reads the
|
||||
DOM and JavaScript state, yes, because that state is identical. For anything
|
||||
reading GPU-dependent rendering or driver-level flags, the display mode is not
|
||||
the variable that matters.
|
||||
|
||||
**See also:**
|
||||
[What navigator.webdriver really tells a site](navigator-webdriver-explained.md),
|
||||
[headless vs headful](headless-vs-headful.md) for the operational trade-offs,
|
||||
and [scraping a site that blocks headless browsers](how-to-scrape-headless-blocked.md)
|
||||
for what to check first when a site specifically challenges headless traffic.
|
||||
|
||||
## Sources
|
||||
|
||||
- [Chromium's own documentation on the new headless mode](https://developer.chrome.com/docs/chromium/headless), retrieved 2026-09-10, for what changed from the old `--headless` implementation.
|
||||
- [MDN, `Navigator.webdriver`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/webdriver), retrieved 2026-09-10, for the flag's spec-defined behaviour independent of display mode.
|
||||
- This project's own fingerprint gates, for the GPU and canvas measurements referenced above.
|
||||
|
||||
---
|
||||
|
||||
*Written while maintaining [invisible_playwright](https://github.com/feder-cr/invisible_playwright),
|
||||
a Firefox patched at the C++ level driven by stock Playwright. This page separates
|
||||
display mode from browser identity because conflating the two sends people
|
||||
switching a setting that was never the cause.*
|
||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "invisible_playwright"
|
||||
version = "0.13.2"
|
||||
version = "0.22.0"
|
||||
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
@@ -69,7 +69,7 @@ dependencies = [
|
||||
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
|
||||
# fails if one appears). What stays invisible to install-time machinery is the
|
||||
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
|
||||
"invisible_core==29.19.0",
|
||||
"invisible_core==31.23.0",
|
||||
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
|
||||
# client lives in src/invisible_playwright/_pw/ and the Node driver in
|
||||
# src/invisible_playwright/_driver/. Reintroducing it would not visibly
|
||||
@@ -223,3 +223,25 @@ exclude = ["tests/playwright-upstream"]
|
||||
pytest = true
|
||||
pin = true
|
||||
release_tags = ["v"]
|
||||
|
||||
# What this repository declares about ITSELF to the shared language gate
|
||||
# (`python -m invisible_core.english`, since invisible-core 30.23.0). The logic
|
||||
# lives in the core, once; only the per-repository half is here. It used to be
|
||||
# a script copied into this repo and into AIHawk, and the copies drifted:
|
||||
# AIHawk's carried these very paths, which exist only here, and this one never
|
||||
# gained the `.js/.css/.html` coverage AIHawk's did.
|
||||
#
|
||||
# Vendored upstream Playwright is excluded as a FOLDER, but our own patches
|
||||
# inside it are still read: they are found by the marker. `injected.js` is
|
||||
# extracted from the upstream bundle. `test_fork.py` carries Italian ON
|
||||
# PURPOSE - its known-bad fixture reproduces a JavaScript comment whose defect
|
||||
# IS the trailing apostrophe of an Italian word; translate it and the mutation
|
||||
# stops reproducing the bug. Named file by file, never by folder: an
|
||||
# exclusion that names nothing is refused by the gate.
|
||||
[tool.invisible.english]
|
||||
excluded = [
|
||||
"src/invisible_playwright/_pw/",
|
||||
"src/invisible_playwright/_juggler/injected.js",
|
||||
"tests/test_fork.py",
|
||||
]
|
||||
marker = "MODIFIED by invisible_playwright"
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render the Jekyll docs/ tree into a GitHub wiki checkout.
|
||||
|
||||
Usage: build_wiki.py <docs_dir> <out_dir>
|
||||
Usage: build_wiki.py <docs_dir> <out_dir> [--pixels <owner/repo>]
|
||||
|
||||
A GitHub wiki is a flat set of <Page>.md files with no Jekyll front matter and a
|
||||
_Sidebar.md for navigation. This converter, for every docs/*.md:
|
||||
@@ -9,12 +9,31 @@ _Sidebar.md for navigation. This converter, for every docs/*.md:
|
||||
- rewrites internal links [x](slug.md[#a]) -> [x](slug[#a]) (wiki has no .md),
|
||||
- names the page by its slug (stable URLs matching the docs site), except
|
||||
index.md -> Home.md (the wiki landing page),
|
||||
- and, with --pixels, gives the page its view counter (see
|
||||
scripts/sync_article_pixels.py for what that number is and is not).
|
||||
and then generates _Sidebar.md mirroring the parent/has_children/nav_order tree.
|
||||
|
||||
The pixel goes into the WIKI only, never back into docs/. The wiki is the
|
||||
surface that ranks and the surface readers land on; the .md in the repository
|
||||
is served as a JSON payload React mounts, and a counter there would measure
|
||||
almost nothing while putting markup into the source tree.
|
||||
|
||||
Without --pixels (a local preview) no pixel is written at all, rather than one
|
||||
addressed to a guessed repository. A wiki published that way would count
|
||||
nothing while looking entirely normal, so publish-wiki.yml passes the flag AND
|
||||
runs `sync_article_pixels.py --check` over the output before pushing.
|
||||
"""
|
||||
import os, re, sys
|
||||
|
||||
from sync_article_pixels import pixel_tag
|
||||
|
||||
DOCS = sys.argv[1]
|
||||
OUT = sys.argv[2]
|
||||
#: `owner/repo` the pixels address, or None. Not read from the environment
|
||||
#: here: the caller that knows it is the workflow, and a fallback to
|
||||
#: GITHUB_REPOSITORY would make a local run behave differently depending on
|
||||
#: what happens to be exported.
|
||||
PIXELS = sys.argv[sys.argv.index("--pixels") + 1] if "--pixels" in sys.argv else None
|
||||
|
||||
def parse(path):
|
||||
t = open(path, encoding="utf-8").read()
|
||||
@@ -88,13 +107,41 @@ def rewrite(body):
|
||||
# `[a-z0-9/-]` and an optional `.md`: a link into a subdirectory carries the
|
||||
# slash and may or may not carry the extension, and the first version of
|
||||
# this pattern matched neither.
|
||||
return re.sub(r'\]\(([a-z0-9/\-]+)(?:\.md)?(#[A-Za-z0-9\-]+)?\)', repl, body)
|
||||
#
|
||||
# The underscore is in BOTH classes because a heading like "What
|
||||
# invisible_playwright does and does not do here" produces the anchor
|
||||
# `#what-invisible_playwright-does-...`, and an anchor the pattern cannot
|
||||
# match makes the WHOLE link fail to rewrite: it ships to the wiki as
|
||||
# `](geetest-v4-explained.md#...)`, which is a dead link, not a link with a
|
||||
# bad anchor. Measured on 2026-09-08: one such link across 463 pages, and it
|
||||
# was invisible because the page renders fine and only the target 404s.
|
||||
return re.sub(r'\]\(([a-z0-9_/\-]+)(?:\.md)?(#[A-Za-z0-9_\-]+)?\)', repl, body)
|
||||
|
||||
def with_pixel(name, body):
|
||||
"""Put the page's view counter just under its H1.
|
||||
|
||||
Under and not above: the H1 is what the reader and every renderer expect
|
||||
first, and a wiki page whose source starts with an <img> renders an empty
|
||||
first line in some previews. Every page in both corpora starts with an H1
|
||||
once the front matter is off - measured, 524 of 524 - so this is a uniform
|
||||
position rather than a heuristic, and a page that ever stops starting with
|
||||
one gets its pixel appended instead of silently misplaced.
|
||||
"""
|
||||
if not PIXELS:
|
||||
return body
|
||||
tag = pixel_tag(PIXELS, name)
|
||||
lines = body.split("\n")
|
||||
if lines and lines[0].startswith("# "):
|
||||
return "\n".join([lines[0], "", tag] + lines[1:])
|
||||
return body.rstrip("\n") + "\n\n" + tag
|
||||
|
||||
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
written = 0
|
||||
for slug, (fm, body) in pages.items():
|
||||
name = "Home" if slug == "index" else slug
|
||||
open(os.path.join(OUT, name + ".md"), "w", encoding="utf-8", newline="\n").write(rewrite(body) + "\n")
|
||||
open(os.path.join(OUT, name + ".md"), "w", encoding="utf-8", newline="\n").write(
|
||||
with_pixel(name, rewrite(body)) + "\n")
|
||||
written += 1
|
||||
|
||||
def title_of(slug):
|
||||
|
||||
@@ -1,365 +0,0 @@
|
||||
"""This repository is public and English-only. This gate says so mechanically.
|
||||
|
||||
Why it exists, and it is not a style preference. On 2026-08-27 a whole new
|
||||
subsystem - the `_juggler` client, its three generator scripts and its four
|
||||
test files, about four thousand lines - was written in ITALIAN and committed
|
||||
here: module names, class names, public method names, every comment. Nothing
|
||||
caught it. The repo had been English since its first commit, `pytest` was green
|
||||
throughout, and the pre-push hook had no opinion about the language a file is
|
||||
written in.
|
||||
|
||||
A convention that lives only in the heads of the people writing the code is not
|
||||
a convention, it is a habit, and a habit skips a session. It is the same lesson
|
||||
this project already wrote down for gates: an invariant nobody can check is an
|
||||
invariant that drifts.
|
||||
|
||||
python scripts/check_english_only.py # 1 if Italian is found
|
||||
python scripts/check_english_only.py --range A..B # only what a push adds
|
||||
python scripts/check_english_only.py --selftest # 9 mutations, 9 that must not fire
|
||||
|
||||
WHAT IT DOES NOT DO, said out loud because a gate whose limits are unstated
|
||||
gets trusted too far. It does not detect Spanish, French or Portuguese. It does
|
||||
not judge prose quality. It cannot see a single Italian noun with no Italian
|
||||
function word near it: `def calcola(x)` on its own passes. What it catches is
|
||||
Italian PROSE, which is what comments and docstrings are made of, and prose is
|
||||
what actually happened.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
|
||||
#: Italian function words that are not English words, not Python keywords and
|
||||
#: not plausible identifiers. ⛔ The list is deliberately CONSERVATIVE: every
|
||||
#: entry was checked against this repo's existing English files, which must stay
|
||||
#: silent. Words left OUT on purpose, with the reason, because the temptation to
|
||||
#: add them will come back:
|
||||
#:
|
||||
#: `del` - a Python keyword.
|
||||
#: `in`, `a`, `di`, `da`, `no`, `se`, `si`, `e`, `o` - too short, and several
|
||||
#: are English words or ordinary variable names.
|
||||
#: `come` - too easy to reach as a fragment of English prose.
|
||||
#: `solo` - an English word.
|
||||
#: `la`, `le`, `il`, `lo`, `un` - one- and two-letter variable names.
|
||||
#:
|
||||
#: What is left is prose glue. If two of these appear in one file, that file is
|
||||
#: not written in English.
|
||||
ITALIAN = (
|
||||
"perche", "quindi", "questo", "questa", "queste", "questi", "quello",
|
||||
"quella", "quelle", "quelli", "della", "delle", "degli", "dello",
|
||||
"nella", "nelle", "negli", "dalla", "dalle", "dagli", "sulla", "sulle",
|
||||
"alla", "alle", "agli", "sono", "essere", "viene", "vengono", "invece",
|
||||
"anche", "senza", "ogni", "tutto", "tutti", "tutta", "tutte", "cosa",
|
||||
"dove", "quando", "sempre", "cioe", "piu", "gia", "adesso", "allora",
|
||||
"prima", "dopo", "sotto", "sopra", "dentro", "fuori", "verso",
|
||||
"niente", "nessuno", "nessuna", "qualcosa", "qualcuno", "molto",
|
||||
"poco", "troppo", "abbastanza", "soltanto", "oppure", "mentre",
|
||||
"finche", "affinche", "benche", "sebbene", "poiche", "siccome",
|
||||
"quale", "quali", "chiunque", "ovunque", "comunque", "dunque",
|
||||
"infatti", "inoltre", "tuttavia", "eppure", "ancora", "appena",
|
||||
"subito", "spesso", "raramente", "davvero", "proprio", "stesso",
|
||||
"stessa", "stesse", "stessi", "altro", "altra", "altre", "altri",
|
||||
)
|
||||
|
||||
#: ⛔ TWO distinct words, not one occurrence. One is how a false positive is
|
||||
#: born: a proper noun, a quoted string, a URL, a vendor name.
|
||||
THRESHOLD = 2
|
||||
|
||||
#: What this gate does not own, and why each entry is here.
|
||||
#:
|
||||
#: ⛔ THE LAST ONE IS A SELF-EXEMPTION AND HAS TO BE JUSTIFIED, not hidden. This
|
||||
#: file carries its own known-bad corpus: the mutations below ARE Italian prose,
|
||||
#: because a gate that has only ever printed PASS is not a gate. The corpus has
|
||||
#: to live somewhere, and the honest place is next to the check that uses it.
|
||||
#: The exemption is exactly one path - never a prefix - and a must-not-fire case
|
||||
#: at the bottom asserts that a sibling script is still covered.
|
||||
EXCLUDED = (
|
||||
"src/invisible_playwright/_pw/", # vendored upstream Playwright
|
||||
"src/invisible_playwright/_driver/", # vendored Node driver bundle
|
||||
"src/invisible_playwright/_juggler/injected.js", # extracted from the bundle
|
||||
"scripts/check_english_only.py", # this file: the known-bad corpus
|
||||
# ⛔ `test_fork.py` carries Italian ON PURPOSE and it cannot be
|
||||
# translated: its known-bad fixture reproduces the JavaScript comment
|
||||
# that broke the driver bundle on 2026-08-24, and the defect IS the
|
||||
# trailing apostrophe of the Italian word `piu'`, which closes the
|
||||
# single-quoted string it sits in. Translate it and the mutation stops
|
||||
# reproducing the bug. Named file by file, never by folder.
|
||||
"tests/test_fork.py",
|
||||
)
|
||||
|
||||
EXTENSIONS = (".py", ".md", ".toml", ".cfg", ".yml", ".yaml")
|
||||
|
||||
|
||||
def italian_words(text: str) -> set:
|
||||
"""The Italian function words present, as a set."""
|
||||
lowered = text.lower()
|
||||
return {w for w in ITALIAN
|
||||
if re.search(r"(?<![a-z0-9_])%s(?![a-z0-9_])" % w, lowered)}
|
||||
|
||||
|
||||
#: The marker our patches carry inside vendored files.
|
||||
#: ⛔ VENDORED IS NOT A BLANKET EXEMPTION, and this is the hole the first
|
||||
#: version of this gate had. `_pw/` and `_driver/` are upstream code we do not
|
||||
#: own, so scanning them whole would be noise - but they contain OUR patches,
|
||||
#: and on 2026-08-27 seven of those blocks were in Italian and completely
|
||||
#: invisible here: `_playwright.py`, `_driver.py`, `__main__.py` and four
|
||||
#: blocks inside the two `_generated.py`. The exclusion is by FOLDER; what is
|
||||
#: ours is identified by this marker, so inside an excluded path the gate reads
|
||||
#: the marked blocks and nothing else.
|
||||
OUR_MARKER = "MODIFIED by invisible_playwright"
|
||||
|
||||
#: ⛔ A PATCH BLOCK IS THE CONTIGUOUS RUN OF COMMENT LINES AROUND THE MARKER,
|
||||
#: never a fixed number of lines. A fixed span was tried first and is wrong in
|
||||
#: both directions: too small it truncates the 41-line block in `_driver.py`,
|
||||
#: too large it reaches past a one-line comment into somebody else's code and
|
||||
#: reports their words as ours. Measured with span 44: two files were flagged
|
||||
#: for Italian that sat in upstream code below the patch.
|
||||
COMMENT_STARTS = ("//", "#")
|
||||
MAX_BLOCK = 80
|
||||
|
||||
#: ⛔ A LINE IS NOT A UNIT IN A BUNDLED FILE, and reading it as one made this
|
||||
#: gate useless the first time it saw `coreBundle.js`: that file has lines of
|
||||
#: 320.820 characters, because the injected sources are single-quoted strings
|
||||
#: with their newlines written as two characters. Taking "16 lines after the
|
||||
#: marker" there swallowed the entire injected script, so the gate reported
|
||||
#: Italian that belonged to upstream code hundreds of kilobytes away from any
|
||||
#: patch of ours. Above this width a line is scanned by CHARACTER window
|
||||
#: instead.
|
||||
LONG_LINE = 2000
|
||||
|
||||
#: How much of a long line belongs to one comment, and where it stops. The
|
||||
#: literal two-character `\n` is the real line break inside those strings.
|
||||
WINDOW = 700
|
||||
BEFORE = 200
|
||||
NL_LITERAL = chr(92) + "n"
|
||||
|
||||
|
||||
def our_blocks(text: str) -> str:
|
||||
"""Only the parts of a vendored file that OUR patches wrote."""
|
||||
lines = text.splitlines()
|
||||
kept: list = []
|
||||
for i, line in enumerate(lines):
|
||||
if OUR_MARKER not in line:
|
||||
continue
|
||||
if len(line) <= LONG_LINE:
|
||||
start = i
|
||||
while (start > 0
|
||||
and lines[start - 1].strip().startswith(COMMENT_STARTS)
|
||||
and i - start < MAX_BLOCK):
|
||||
start -= 1
|
||||
end = i
|
||||
while (end + 1 < len(lines)
|
||||
and lines[end + 1].strip().startswith(COMMENT_STARTS)
|
||||
and end - i < MAX_BLOCK):
|
||||
end += 1
|
||||
kept.extend(lines[start:end + 1])
|
||||
continue
|
||||
pos = 0
|
||||
while True:
|
||||
j = line.find(OUR_MARKER, pos)
|
||||
if j < 0:
|
||||
break
|
||||
end = line.find(NL_LITERAL, j)
|
||||
if not 0 < end - j < WINDOW:
|
||||
end = j + WINDOW
|
||||
kept.append(line[max(0, j - BEFORE):end])
|
||||
pos = j + 1
|
||||
return "\n".join(kept)
|
||||
|
||||
|
||||
def inspect(path: str, text: str) -> tuple:
|
||||
"""(is_italian, words) for one file.
|
||||
|
||||
A pure function on (path, text): the selftest mutates here and never
|
||||
touches the disk, which is what makes the mutations cost nothing to run.
|
||||
"""
|
||||
normalised = path.replace(chr(92), "/")
|
||||
if normalised in EXCLUDED:
|
||||
return (False, set())
|
||||
if any(e.endswith("/") and normalised.startswith(e) for e in EXCLUDED):
|
||||
# ⛔ Excluded as a FOLDER, but our own patches inside it are still ours.
|
||||
found = italian_words(our_blocks(text))
|
||||
return (len(found) >= THRESHOLD, found)
|
||||
if not normalised.endswith(EXTENSIONS):
|
||||
return (False, set())
|
||||
found = italian_words(text)
|
||||
return (len(found) >= THRESHOLD, found)
|
||||
|
||||
|
||||
def tracked(rev_range=None) -> list:
|
||||
"""The files to look at: everything tracked, or only what a range touches."""
|
||||
if rev_range:
|
||||
r = subprocess.run(
|
||||
["git", "diff", "--name-only", "--diff-filter=d", rev_range],
|
||||
cwd=ROOT, capture_output=True, text=True)
|
||||
else:
|
||||
r = subprocess.run(["git", "ls-files"], cwd=ROOT,
|
||||
capture_output=True, text=True)
|
||||
if r.returncode:
|
||||
raise RuntimeError("git refused: %s" % r.stderr.strip()[:200])
|
||||
return [x for x in r.stdout.splitlines() if x.strip()]
|
||||
|
||||
|
||||
def scan(paths) -> list:
|
||||
guilty = []
|
||||
for path in paths:
|
||||
f = ROOT / path
|
||||
if not f.exists():
|
||||
continue
|
||||
try:
|
||||
text = f.read_bytes().decode("utf-8")
|
||||
except (UnicodeDecodeError, OSError):
|
||||
continue
|
||||
is_italian, found = inspect(path, text)
|
||||
if is_italian:
|
||||
guilty.append((path, sorted(found)))
|
||||
return guilty
|
||||
|
||||
|
||||
# ── the selftest ────────────────────────────────────────────────────────────
|
||||
def selftest() -> int:
|
||||
# ⛔ The known-bad corpus. It is Italian on purpose, and it is the reason
|
||||
# this file exempts itself above.
|
||||
ITA = ("# Questo commento e' scritto in italiano perche' nessuno "
|
||||
"controllava.\ndef f():\n return 1\n")
|
||||
ENG = ("# This comment is in English, which is what the repo uses.\n"
|
||||
"def f():\n return 1\n")
|
||||
bad = 0
|
||||
|
||||
def expect(name, path, text, should_fire):
|
||||
nonlocal bad
|
||||
is_italian, found = inspect(path, text)
|
||||
if is_italian != should_fire:
|
||||
print(" %s: %s (words seen: %s)"
|
||||
% ("SURVIVED" if should_fire else "FALSE POSITIVE",
|
||||
name, sorted(found) or "none"))
|
||||
bad += 1
|
||||
else:
|
||||
print(" %s: %s" % ("killed" if should_fire else "silent", name))
|
||||
|
||||
print("--- mutations that MUST fire ---")
|
||||
expect("an Italian comment in a .py", "src/x.py", ITA, True)
|
||||
expect("an Italian document", "README.md", ITA, True)
|
||||
expect("Italian inside a docstring", "src/x.py",
|
||||
'def f():\n """Questo fa qualcosa, quindi serve."""\n', True)
|
||||
expect("Italian in a config file", "pyproject.toml",
|
||||
"# Questo pacchetto, quindi, dipende da\nname = 'x'\n", True)
|
||||
# ⛔ The real case: names translated, comments not. That is what a
|
||||
# half-finished translation looks like, and it is the likeliest way to
|
||||
# get this wrong a second time.
|
||||
expect("English names, Italian comments", "src/x.py",
|
||||
"def click(selector):\n"
|
||||
" # Prima si risolve, poi si guarda dove sta, quindi si clicca.\n"
|
||||
" return selector\n", True)
|
||||
expect("an Italian test", "tests/test_x.py",
|
||||
"def test_questo_funziona():\n"
|
||||
" # Questo controlla che tutto sia a posto, quindi basta.\n"
|
||||
" assert True\n", True)
|
||||
expect("Italian in a sibling script", "scripts/gen_x.py", ITA, True)
|
||||
expect("Italian in a workflow", ".github/workflows/ci.yml",
|
||||
"# Questo lavoro gira sempre, quindi non si salta.\nname: ci\n", True)
|
||||
|
||||
# ⛔ The hole this gate had until 2026-08-27: `_pw/` is excluded as a
|
||||
# folder, and our own patches inside it went unread. Seven blocks were in
|
||||
# Italian, one of them in `_playwright.py`, which every user imports.
|
||||
OUR_ITA = "\n".join([
|
||||
"def upstream(self):",
|
||||
" # MODIFIED by invisible_playwright: chromium e webkit non",
|
||||
" # esistono piu' in questo fork, quindi il messaggio lo dice",
|
||||
" # invece di lasciare un AttributeError.",
|
||||
" raise ValueError('x')",
|
||||
]) + "\n"
|
||||
expect("OUR patch inside a vendored file",
|
||||
"src/invisible_playwright/_pw/_impl/_playwright.py",
|
||||
OUR_ITA, True)
|
||||
|
||||
print("--- cases that must NOT fire ---")
|
||||
expect("ordinary English", "src/x.py", ENG, False)
|
||||
# ⛔ One word is not prose, and this is the line that keeps false positives
|
||||
# out: a proper noun, a quoted string, a URL.
|
||||
expect("a single Italian word (a name, a quotation)", "src/x.py",
|
||||
"# The vendor is called Sempre, which is a name and not a sentence.\n",
|
||||
False)
|
||||
expect("vendored Playwright is not ours",
|
||||
"src/invisible_playwright/_pw/_impl/_page.py", ITA, False)
|
||||
expect("the vendored driver is not ours",
|
||||
"src/invisible_playwright/_driver/package/lib/x.py", ITA, False)
|
||||
# ⛔ But OUR patch inside a vendored file IS ours. Without this the gate
|
||||
# had a hole seven blocks wide, and the biggest of them sat in a file every
|
||||
# user imports.
|
||||
# ⛔ A minified line is not a unit: 320.820 characters of upstream code
|
||||
# around one patch of ours must not be read as part of it. Without the
|
||||
# character window this fired on `coreBundle.js` for Italian that belonged
|
||||
# to nobody.
|
||||
MINIFIED = ("var a=1;" + ("x" * 3000)
|
||||
+ " // questo e' upstream, quindi non si guarda affatto "
|
||||
+ ("y" * 3000)
|
||||
+ " // MODIFIED by invisible_playwright: nothing to see here "
|
||||
+ ("z" * 3000)
|
||||
+ " // e anche questo e' upstream, dunque niente" + "\n")
|
||||
expect("a minified line around our patch",
|
||||
"src/invisible_playwright/_driver/package/lib/coreBundle.js",
|
||||
MINIFIED, False)
|
||||
expect("upstream code around our patch stays invisible",
|
||||
"src/invisible_playwright/_pw/_impl/_page.py",
|
||||
"\n".join(["# questo e' upstream, quindi non lo guardiamo affatto",
|
||||
"def upstream_thing():",
|
||||
" return 1"]) + "\n", False)
|
||||
expect("a binary has no language", "assets/logo.png", ITA, False)
|
||||
# ⛔ The self-exemption must be ONE PATH, never a prefix: a prefix would
|
||||
# quietly stop covering every other script in the folder.
|
||||
expect("this file, which carries the corpus",
|
||||
"scripts/check_english_only.py", ITA, False)
|
||||
|
||||
# ⛔ And the check that is worth more than all the others: the gate must be
|
||||
# SILENT on this repository as it stands. A gate born red on what already
|
||||
# exists teaches people to bypass it, and this project has written that
|
||||
# down twice.
|
||||
print("--- the real repository ---")
|
||||
try:
|
||||
noisy = scan(tracked())
|
||||
if noisy:
|
||||
print(" %d files are still in Italian:" % len(noisy))
|
||||
for path, found in noisy[:12]:
|
||||
print(" %-58s %s" % (path, ", ".join(found[:4])))
|
||||
if len(noisy) > 12:
|
||||
print(" ... and %d more" % (len(noisy) - 12))
|
||||
bad += 1
|
||||
else:
|
||||
print(" silent: no tracked file is in Italian")
|
||||
except RuntimeError as failure:
|
||||
print(" not verifiable (%s)" % failure)
|
||||
|
||||
print()
|
||||
print("selftest: %s" % ("ALL GOOD" if not bad else "%d PROBLEMS" % bad))
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--range", dest="rev_range",
|
||||
help="only the files a range touches, e.g. origin/main..HEAD")
|
||||
p.add_argument("--selftest", action="store_true")
|
||||
a = p.parse_args()
|
||||
if a.selftest:
|
||||
return selftest()
|
||||
|
||||
guilty = scan(tracked(a.rev_range))
|
||||
if not guilty:
|
||||
print("english only: clean")
|
||||
return 0
|
||||
print("%d file(s) are not in English:" % len(guilty))
|
||||
for path, found in guilty:
|
||||
print(" %-58s %s" % (path, ", ".join(found[:6])))
|
||||
print()
|
||||
print("This repository is public and English-only. Translate these files.")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -97,6 +97,16 @@ def main() -> int:
|
||||
# MUST contain costs nothing and stops us from shipping the wrong blob.
|
||||
EXPECTED = ("InjectedScript", "internal:role", "internal:testid",
|
||||
"_setupHitTargetInterceptors", "createRoleEngine")
|
||||
#
|
||||
# ⛔ `_setupHitTargetInterceptors` IS STILL THE RIGHT FINGERPRINT even
|
||||
# though the shipped `injected.js` no longer has it. This tuple describes the
|
||||
# bundle we EXTRACT FROM, which is upstream's and still carries it; our
|
||||
# removal happens after. Do not delete the name because a grep for removed
|
||||
# symbols lands here.
|
||||
#
|
||||
# What catches a regeneration that quietly brings the mechanism back is
|
||||
# `tests/test_injected_page_surface.py`: constructing the InjectedScript
|
||||
# would touch the page's window again, and the gate goes red.
|
||||
missing = [x for x in EXPECTED if x not in source]
|
||||
if missing:
|
||||
raise SystemExit("the extract does not look like the injected script: "
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One view pixel per wiki page, and the release that holds them.
|
||||
|
||||
A GitHub wiki serves no per-page analytics. The repository traffic API reports
|
||||
the ten most visited paths over fourteen days and nothing below that, so a
|
||||
corpus of hundreds of wiki pages is invisible by construction: measured on this
|
||||
repository, the whole wiki index sits at about thirty views per fortnight and
|
||||
not one individual page reaches the top ten.
|
||||
|
||||
This gives every page a counter of its own, by the same mechanism the browser
|
||||
launch counter has used since May: a release asset whose `download_count` is
|
||||
incremented by GitHub on every fetch. Each wiki page embeds its own asset as a
|
||||
1x1 transparent image, so one page view is one fetch is one count. The assets
|
||||
live in a release tagged `article-views`, which is not a software release and
|
||||
is created with `make_latest=false` so it never becomes the repository's
|
||||
"Latest".
|
||||
|
||||
What the number is, said once so nobody reads it as more than it is:
|
||||
|
||||
* It counts FETCHES, not people. A reader who opens a page twice counts
|
||||
twice, and there is no unique-visitor figure anywhere in it.
|
||||
* It counts every client that loads images, crawlers included. Image
|
||||
indexers and link unfurlers fetch it exactly like a browser does. At the
|
||||
per-page volumes above, that share is not small.
|
||||
* It undercounts readers who block images or read the page through a proxy
|
||||
that strips them.
|
||||
|
||||
It is a floor with noise on top, and it is the only per-page signal available.
|
||||
GitHub's own `traffic/popular/paths` is the independent instrument that can
|
||||
corroborate it: a page the pixel calls the most read should, eventually, show
|
||||
up in that top ten.
|
||||
|
||||
Usage:
|
||||
|
||||
python scripts/sync_article_pixels.py --repo owner/name wiki_build
|
||||
python scripts/sync_article_pixels.py --repo owner/name --check wiki_build
|
||||
python scripts/sync_article_pixels.py --selftest
|
||||
|
||||
`--check` is the gate: it refuses unless every built page carries exactly one
|
||||
pixel, addressed to this repository and naming that page. It exists because
|
||||
the injection happens in `build_wiki.py`, which falls back to no pixel at all
|
||||
when it is not told which repository it is building for - and a wiki published
|
||||
without pixels counts nothing while looking perfectly normal.
|
||||
|
||||
The sync NEVER deletes an asset. A page removed from `docs/` keeps its history,
|
||||
and a renamed slug gets a new asset rather than inheriting the old one's count,
|
||||
which is the truth: the wiki has no redirects, so a renamed page is a new URL.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
#: The release that holds the pixels. Not a software release: `publish.yml`
|
||||
#: reads `v*` tags and never looks at this one.
|
||||
TAG = "article-views"
|
||||
|
||||
#: GitHub allows 1000 assets on a single release. Refusing well short of that
|
||||
#: leaves room to notice and split into a second release, rather than finding
|
||||
#: out from a failed upload on the day a page is published.
|
||||
MAX_ASSETS = 1000
|
||||
REFUSE_ABOVE = 950
|
||||
|
||||
#: `_Sidebar.md` is navigation injected into every page, not a page. A pixel
|
||||
#: there would fire on every view of every page and drown its own signal.
|
||||
NOT_A_PAGE = {"_Sidebar", "_Footer", "_Header"}
|
||||
|
||||
#: Any pixel, whichever repository or page it names. The check needs to see a
|
||||
#: WRONG pixel, not only a missing one, so it matches the shape and compares
|
||||
#: the parts afterwards.
|
||||
PIXEL_RE = re.compile(
|
||||
r'<img src="https://github\.com/([^/"]+/[^/"]+)/releases/download/'
|
||||
+ TAG + r'/([^"/]+)\.png" width="1" height="1" alt="">')
|
||||
|
||||
|
||||
def pixel_bytes() -> bytes:
|
||||
"""A 1x1 fully transparent PNG, built here rather than committed.
|
||||
|
||||
68 bytes, and no image library on the runner. Transparent so it cannot
|
||||
show through any theme, and a real PNG so a browser that sniffs content
|
||||
types is not handed a text file with an image extension.
|
||||
"""
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return (struct.pack(">I", len(data)) + kind + data
|
||||
+ struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff))
|
||||
ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0) # 1x1, 8-bit RGBA
|
||||
idat = zlib.compress(b"\x00" + b"\x00\x00\x00\x00") # one filtered row
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr)
|
||||
+ chunk(b"IDAT", idat) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def pixel_tag(repo: str, page: str) -> str:
|
||||
"""The exact markup a page carries.
|
||||
|
||||
ONE definition, imported by `build_wiki.py` which writes it and by the
|
||||
check below which verifies it. Two copies of this string would agree today
|
||||
and drift the first time either side is edited, and the failure would be a
|
||||
wiki that silently stops counting.
|
||||
|
||||
`alt=""` marks it decorative, so a screen reader skips it and a broken
|
||||
fetch leaves nothing visible. GitHub renders images from `github.com`
|
||||
directly rather than through its camo proxy, so the reader's browser asks
|
||||
GitHub for this asset and GitHub counts the request.
|
||||
"""
|
||||
return ('<img src="https://github.com/%s/releases/download/%s/%s.png"'
|
||||
' width="1" height="1" alt="">' % (repo, TAG, page))
|
||||
|
||||
|
||||
def page_names(wiki_dir: str | Path) -> list[str]:
|
||||
"""The built wiki pages that get a pixel, by page name (no extension)."""
|
||||
return sorted(p.stem for p in Path(wiki_dir).glob("*.md")
|
||||
if p.stem not in NOT_A_PAGE)
|
||||
|
||||
|
||||
def check(wiki_dir: str | Path, repo: str) -> list[str]:
|
||||
"""Every page carries exactly one pixel, for THIS repo and THIS page."""
|
||||
problems = []
|
||||
for p in sorted(Path(wiki_dir).glob("*.md")):
|
||||
found = PIXEL_RE.findall(p.read_text(encoding="utf-8"))
|
||||
if p.stem in NOT_A_PAGE:
|
||||
if found:
|
||||
problems.append("%s is not a page and carries a pixel" % p.name)
|
||||
continue
|
||||
if not found:
|
||||
problems.append("%s carries no pixel" % p.name)
|
||||
elif len(found) > 1:
|
||||
problems.append("%s carries %d pixels" % (p.name, len(found)))
|
||||
else:
|
||||
got_repo, got_page = found[0]
|
||||
if got_repo != repo:
|
||||
problems.append("%s points at %s, not %s"
|
||||
% (p.name, got_repo, repo))
|
||||
if got_page != p.stem:
|
||||
problems.append("%s carries the pixel of %s"
|
||||
% (p.name, got_page))
|
||||
return problems
|
||||
|
||||
|
||||
def _api(url: str, token: str, data: bytes | None = None,
|
||||
ctype: str = "application/json", method: str | None = None,
|
||||
tries: int = 5, sleep=time.sleep):
|
||||
"""One API call, with the secondary rate limit handled rather than met.
|
||||
|
||||
The first run on an existing corpus uploads one asset per page - 463 on
|
||||
the engine - and GitHub throttles bursts of content-creating requests with
|
||||
a 403 or 429 carrying `Retry-After`. Without this the first run is the one
|
||||
that fails, and it fails BEFORE the wiki push, so a hiccup here would block
|
||||
the publish entirely. Honouring the header is also what rule 11 asks for
|
||||
everywhere else this project talks to GitHub.
|
||||
|
||||
A 404 is raised, not retried: `release()` reads one to decide the release
|
||||
has to be created.
|
||||
"""
|
||||
for attempt in range(tries):
|
||||
req = urllib.request.Request(url, data=data, method=method)
|
||||
req.add_header("Authorization", "Bearer " + token)
|
||||
req.add_header("Accept", "application/vnd.github+json")
|
||||
if data is not None:
|
||||
req.add_header("Content-Type", ctype)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
return json.load(r)
|
||||
except urllib.error.HTTPError as e:
|
||||
last_try = attempt == tries - 1
|
||||
if e.code not in (403, 429, 500, 502, 503) or last_try:
|
||||
raise
|
||||
wait = e.headers.get("Retry-After")
|
||||
wait = int(wait) if wait and wait.isdigit() else 2 ** attempt
|
||||
print("[pixels] %s from GitHub, waiting %ds (attempt %d of %d)"
|
||||
% (e.code, wait, attempt + 1, tries), file=sys.stderr)
|
||||
sleep(wait)
|
||||
|
||||
|
||||
def release(repo: str, token: str) -> dict:
|
||||
"""The pixel release, created on first use."""
|
||||
try:
|
||||
return _api("https://api.github.com/repos/%s/releases/tags/%s"
|
||||
% (repo, TAG), token)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 404:
|
||||
raise
|
||||
body = ("One tiny image per wiki page. The download count of each asset is"
|
||||
" how many times that page was viewed. This is not a software"
|
||||
" release: see scripts/sync_article_pixels.py.")
|
||||
return _api("https://api.github.com/repos/%s/releases" % repo, token,
|
||||
json.dumps({"tag_name": TAG, "name": "Article views",
|
||||
"body": body, "draft": False, "prerelease": False,
|
||||
"make_latest": "false"}).encode(), method="POST")
|
||||
|
||||
|
||||
def existing_assets(repo: str, rel_id: int, token: str) -> dict[str, int]:
|
||||
"""Asset name -> download count, ALL of them.
|
||||
|
||||
Paginated deliberately. The assets embedded in a release object are capped
|
||||
by the API, so reading them from there would silently report a corpus of
|
||||
hundreds of pages as a few dozen, and the sync would re-upload assets that
|
||||
already exist (which fails) or the reader would lose pages (which is
|
||||
worse, because it looks like zero views).
|
||||
"""
|
||||
out: dict[str, int] = {}
|
||||
page = 1
|
||||
while True:
|
||||
batch = _api("https://api.github.com/repos/%s/releases/%d/assets"
|
||||
"?per_page=100&page=%d" % (repo, rel_id, page), token)
|
||||
if not batch:
|
||||
return out
|
||||
for a in batch:
|
||||
out[a["name"]] = a["download_count"]
|
||||
page += 1
|
||||
|
||||
|
||||
def sync(wiki_dir: str | Path, repo: str, token: str) -> int:
|
||||
pages = page_names(wiki_dir)
|
||||
rel = release(repo, token)
|
||||
have = existing_assets(repo, rel["id"], token)
|
||||
missing = [p for p in pages if p + ".png" not in have]
|
||||
total = len(have) + len(missing)
|
||||
if total > REFUSE_ABOVE:
|
||||
print("[pixels] REFUSING: %d assets would be on one release, and"
|
||||
" GitHub allows %d. Split the corpus across a second release"
|
||||
" before publishing more pages." % (total, MAX_ASSETS),
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
if not missing:
|
||||
print("[pixels] %d pages, all already have an asset" % len(pages))
|
||||
return 0
|
||||
png = pixel_bytes()
|
||||
upload = rel["upload_url"].split("{")[0]
|
||||
for i, name in enumerate(missing, 1):
|
||||
_api("%s?name=%s.png" % (upload, name), token, png, "image/png", "POST")
|
||||
# Paced, not raced. A tenth of a second puts the whole first run under
|
||||
# a minute of added wall clock and keeps a 463-asset burst well inside
|
||||
# what GitHub serves without throttling; the retry above is what
|
||||
# catches it if this is not enough.
|
||||
if i % 50 == 0:
|
||||
print("[pixels] uploaded %d of %d" % (i, len(missing)))
|
||||
time.sleep(0.1)
|
||||
print("[pixels] %d pages, uploaded %d new asset(s): %s"
|
||||
% (len(pages), len(missing), ", ".join(missing[:10])
|
||||
+ (" ..." if len(missing) > 10 else "")))
|
||||
return 0
|
||||
|
||||
|
||||
def selftest() -> int:
|
||||
"""Known-bad inputs. A check that has only ever passed is not a check."""
|
||||
import tempfile
|
||||
repo = "feder-cr/invisible_playwright"
|
||||
good = pixel_tag(repo, "a-page")
|
||||
cases = [
|
||||
("a page with its own pixel passes",
|
||||
{"a-page.md": "# T\n\n" + good + "\n"}, 0),
|
||||
("a page with no pixel fails",
|
||||
{"a-page.md": "# T\n\nbody\n"}, 1),
|
||||
("a pixel for another repo fails",
|
||||
{"a-page.md": "# T\n\n" + pixel_tag("feder-cr/AIHawk", "a-page")}, 1),
|
||||
("a pixel naming another page fails",
|
||||
{"a-page.md": "# T\n\n" + pixel_tag(repo, "other-page")}, 1),
|
||||
("two pixels on one page fail",
|
||||
{"a-page.md": "# T\n\n" + good + "\n" + good}, 1),
|
||||
("the sidebar without a pixel passes",
|
||||
{"a-page.md": "# T\n\n" + good, "_Sidebar.md": "### nav\n"}, 0),
|
||||
("the sidebar WITH a pixel fails",
|
||||
{"a-page.md": "# T\n\n" + good,
|
||||
"_Sidebar.md": pixel_tag(repo, "_Sidebar")}, 1),
|
||||
]
|
||||
bad = []
|
||||
for label, files, expected in cases:
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for n, t in files.items():
|
||||
(Path(d) / n).write_text(t, encoding="utf-8")
|
||||
got = len(check(d, repo))
|
||||
ok = (got > 0) == (expected > 0)
|
||||
print(" %s %s" % ("OK" if ok else "KO", label))
|
||||
if not ok:
|
||||
bad.append(label)
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for n in ("one.md", "two.md", "_Sidebar.md", "notes.txt"):
|
||||
(Path(d) / n).write_text("x", encoding="utf-8")
|
||||
names = page_names(d)
|
||||
|
||||
# The retry, against a server that throttles. Without these three cases the
|
||||
# backoff would be code that has never once run: the path only opens on a
|
||||
# 403 from a burst, which is exactly the run nobody gets to rehearse.
|
||||
import io
|
||||
real_urlopen = urllib.request.urlopen
|
||||
|
||||
class _Resp(io.BytesIO):
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *a): return False
|
||||
|
||||
def _fake_opener(sequence):
|
||||
left = list(sequence)
|
||||
def opener(req, timeout=None):
|
||||
outcome = left.pop(0)
|
||||
if outcome is None:
|
||||
return _Resp(b'{"ok": true}')
|
||||
raise urllib.error.HTTPError(req.full_url, outcome, "throttled",
|
||||
{"Retry-After": "1"}, None)
|
||||
return opener
|
||||
|
||||
slept = []
|
||||
api_cases = []
|
||||
for label, sequence, must_raise in (
|
||||
("a 403 with Retry-After is retried and then passes", [403, None], False),
|
||||
("a 429 is retried", [429, 429, None], False),
|
||||
("a 404 is NOT retried: it is how a missing release is found",
|
||||
[404], True),
|
||||
("the attempts run out and the error comes through", [403, 403, 403], True),
|
||||
):
|
||||
urllib.request.urlopen = _fake_opener(sequence)
|
||||
try:
|
||||
_api("https://example.invalid/x", "t", tries=3,
|
||||
sleep=lambda s: slept.append(s))
|
||||
raised = False
|
||||
except urllib.error.HTTPError:
|
||||
raised = True
|
||||
finally:
|
||||
urllib.request.urlopen = real_urlopen
|
||||
api_cases.append((label, raised == must_raise))
|
||||
api_cases.append(("l'wait viene dall'header Retry-After",
|
||||
slept and all(s == 1 for s in slept)))
|
||||
for label, ok in api_cases:
|
||||
print(" %s %s" % ("OK" if ok else "KO", label))
|
||||
if not ok:
|
||||
bad.append(label)
|
||||
|
||||
png = pixel_bytes()
|
||||
extra = (
|
||||
("the pixel is a PNG", png.startswith(b"\x89PNG\r\n\x1a\n")),
|
||||
("the pixel is 1x1", struct.unpack(">II", png[16:24]) == (1, 1)),
|
||||
("the pixel has an alpha channel", png[25] == 6),
|
||||
("page_names lists the pages", names == ["one", "two"]),
|
||||
)
|
||||
for label, ok in extra:
|
||||
print(" %s %s" % ("OK" if ok else "KO", label))
|
||||
if not ok:
|
||||
bad.append(label)
|
||||
print("selftest: %d cases, %d broken"
|
||||
% (len(cases) + len(extra) + len(api_cases), len(bad)))
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("wiki_dir", nargs="?")
|
||||
ap.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY"))
|
||||
ap.add_argument("--check", action="store_true")
|
||||
ap.add_argument("--selftest", action="store_true")
|
||||
a = ap.parse_args()
|
||||
if a.selftest:
|
||||
return selftest()
|
||||
if not a.wiki_dir or not a.repo:
|
||||
ap.error("a wiki directory and --repo (or GITHUB_REPOSITORY) are needed")
|
||||
if a.check:
|
||||
problems = check(a.wiki_dir, a.repo)
|
||||
for p in problems:
|
||||
print("[pixels] " + p, file=sys.stderr)
|
||||
print("[pixels] checked %d pages, %d problem(s)"
|
||||
% (len(page_names(a.wiki_dir)), len(problems)))
|
||||
return 1 if problems else 0
|
||||
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
|
||||
if not token:
|
||||
print("[pixels] no GITHUB_TOKEN", file=sys.stderr)
|
||||
return 1
|
||||
return sync(a.wiki_dir, a.repo, token)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -89,6 +89,9 @@ from typing import Any, Callable, Iterable, List, Optional, Sequence, Tuple
|
||||
__all__ = [
|
||||
"Step",
|
||||
"PointerPersona",
|
||||
"TypingPersona",
|
||||
"plan_typing",
|
||||
"plan_click",
|
||||
"PlanStats",
|
||||
"initial_pointer",
|
||||
"landing_point",
|
||||
@@ -147,6 +150,19 @@ def _clamp(v: float, lo: float, hi: float) -> float:
|
||||
return lo if v < lo else (hi if v > hi else v)
|
||||
|
||||
|
||||
def _log_normal(rng: random.Random, median: float, sigma: float) -> float:
|
||||
"""A right-skewed draw whose MEDIAN is `median`.
|
||||
|
||||
⛔ The median, not the mean, and the distinction is the reason this helper
|
||||
exists rather than a `gauss` at each call site. Human timings - a keystroke
|
||||
gap, a pause, a movement time - have a floor and a long tail, so their mean
|
||||
sits above their typical value and a symmetric draw around the mean puts
|
||||
too much mass below the floor. `exp(gauss(log(m), s))` has median `m` by
|
||||
construction.
|
||||
"""
|
||||
return median * math.exp(rng.gauss(0.0, sigma))
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────
|
||||
# Step
|
||||
# ──────────────────────────────────────────────────────────────────────
|
||||
@@ -275,6 +291,25 @@ class PointerPersona:
|
||||
# negative (100% of movements ending on a control is not a hand), not a
|
||||
# measured human rate.
|
||||
aimless_rate: float
|
||||
# ⛔ THE THREE BELOW ARE DRAWN LAST, AND THAT IS LOAD BEARING. `from_seed`
|
||||
# draws in order from one stream, so a field inserted ABOVE any existing
|
||||
# one would shift every draw after it and change what every existing seed
|
||||
# produces - silently, for a property this package documents and users rely
|
||||
# on. New fields go at the end. Verified by comparing the other fields
|
||||
# against the previous release for three seeds.
|
||||
#
|
||||
# How long a mouse button stays down for one click.
|
||||
# [judg] informed by the same body of work as the key dwell: a deliberate
|
||||
# click sits around 60-120 ms, and what came out before was the cost of one
|
||||
# protocol round trip.
|
||||
click_dwell_median_ms: float
|
||||
click_dwell_sigma: float
|
||||
# Between the two presses of a double click. [lit] operating systems accept
|
||||
# a double click up to about 500 ms apart and people land well inside that,
|
||||
# around 100-250 ms. Below a few tens of ms is a number no hand produces,
|
||||
# and the pair is still delivered as a `dblclick` because the event is born
|
||||
# from `clickCount`, not from the interval.
|
||||
dblclick_gap_median_ms: float
|
||||
|
||||
@classmethod
|
||||
def from_seed(cls, seed: int) -> "PointerPersona":
|
||||
@@ -295,9 +330,165 @@ class PointerPersona:
|
||||
pause_sigma=r.uniform(0.75, 1.25),
|
||||
overshoot_bias=r.uniform(0.55, 1.45),
|
||||
aimless_rate=r.uniform(0.22, 0.48),
|
||||
# ⛔ APPENDED, never inserted: see the note on the fields.
|
||||
click_dwell_median_ms=r.uniform(58.0, 124.0),
|
||||
click_dwell_sigma=r.uniform(0.20, 0.40),
|
||||
dblclick_gap_median_ms=r.uniform(95.0, 215.0),
|
||||
)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────
|
||||
# The hand on the keyboard
|
||||
# ──────────────────────────────────────────────────────────────────────
|
||||
#
|
||||
# ⛔ WHY THIS EXISTS AT ALL. The pointer has had an owner of its rhythm since
|
||||
# 0.4.0 - this module - and the keyboard had none. A keypress went out as two
|
||||
# protocol messages back to back, so the page saw a `keydown` and a `keyup`
|
||||
# about 2.4 ms apart and two characters about 5 ms apart, against the 60-250 ms
|
||||
# a hand produces. It is the cheapest tell there is to collect: a site does not
|
||||
# need to probe for it, it only has to listen, and a password field is exactly
|
||||
# where that listening is already installed.
|
||||
#
|
||||
# The `delay=` parameter was not the fix. It was dropped by the server on six
|
||||
# of the seven paths that accept it, and even honoured it would be a constant
|
||||
# the caller chose: every install that passed `delay=100` would share one
|
||||
# rhythm, which is the linkage key this module exists to remove.
|
||||
|
||||
#: Which hand types each key on a US layout, for the digram effects below.
|
||||
#: ⛔ A FINITE, KNOWN domain, which is the condition that makes a table the
|
||||
#: right shape here rather than something computed. Keys absent from it are
|
||||
#: treated as neither hand, which costs only the digram modulation.
|
||||
_LEFT_HAND = set("`12345qwertasdfgzxcvb~!@#$%QWERTASDFGZXCVB")
|
||||
_RIGHT_HAND = set("67890-=yuiop[]\\hjkl;'nm,./^&*()_+YUIOP{}|HJKL:\"NM<>?")
|
||||
|
||||
|
||||
def _hand(ch: str) -> str:
|
||||
if ch in _LEFT_HAND:
|
||||
return "L"
|
||||
if ch in _RIGHT_HAND:
|
||||
return "R"
|
||||
return "?"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TypingPersona:
|
||||
"""The parameters of one session's typing hand. Drawn from the session seed.
|
||||
|
||||
Same shape as :class:`PointerPersona` and for the same reason: every field
|
||||
is a range, because the centre is an estimate and the width is the
|
||||
admission that people differ. A single hardcoded value would be a constant
|
||||
shared by every install.
|
||||
|
||||
⛔ It is drawn on its OWN tagged stream (`typing-persona`), so adding it
|
||||
does not move a single number any existing seed produces for the pointer.
|
||||
That property is why `_sub_seed` takes a tag at all.
|
||||
"""
|
||||
|
||||
seed: int
|
||||
# How long a key stays down, median of a log-normal.
|
||||
# [judg] informed by keystroke-dynamics work, where hold times for ordinary
|
||||
# typists cluster in the 60-120 ms band. The spread matters more than the
|
||||
# centre: a constant dwell is as recognisable as a zero one.
|
||||
dwell_median_ms: float
|
||||
dwell_sigma: float
|
||||
# Gap between one key going up and the next going down, median of a
|
||||
# log-normal. [judg] continuous prose for a non-expert typist sits around
|
||||
# 120-280 ms per keystroke overall, of which the dwell is a part.
|
||||
gap_median_ms: float
|
||||
gap_sigma: float
|
||||
# Digram modulation. [lit] Alternating hands is FASTER than staying on one
|
||||
# hand, and repeating the same key is slowest of all, which is the most
|
||||
# robust structure in typing timing and the reason a flat interval reads as
|
||||
# machine-made even when its mean is right.
|
||||
alternate_hand_factor: float
|
||||
same_hand_factor: float
|
||||
same_key_factor: float
|
||||
# How often the typist stops to think, and for how long. [judg] the pauses
|
||||
# are what make a real transcript spiky; a distribution with no tail is a
|
||||
# distribution nobody produced.
|
||||
hesitation_rate: float
|
||||
hesitation_median_ms: float
|
||||
|
||||
@classmethod
|
||||
def from_seed(cls, seed: int) -> "TypingPersona":
|
||||
r = _rng(seed, "typing-persona")
|
||||
return cls(
|
||||
seed=seed,
|
||||
dwell_median_ms=r.uniform(62.0, 118.0),
|
||||
dwell_sigma=r.uniform(0.22, 0.42),
|
||||
gap_median_ms=r.uniform(95.0, 235.0),
|
||||
gap_sigma=r.uniform(0.34, 0.62),
|
||||
alternate_hand_factor=r.uniform(0.74, 0.92),
|
||||
same_hand_factor=r.uniform(1.04, 1.24),
|
||||
same_key_factor=r.uniform(1.25, 1.75),
|
||||
hesitation_rate=r.uniform(0.02, 0.07),
|
||||
hesitation_median_ms=r.uniform(420.0, 1250.0),
|
||||
)
|
||||
|
||||
|
||||
def plan_click(persona: PointerPersona, clicks: int = 1,
|
||||
nonce: int = 0) -> List[Tuple[float, float]]:
|
||||
"""One `(dwell_ms, gap_ms)` per press of a click or a double click.
|
||||
|
||||
`dwell_ms` is how long the button stays down; `gap_ms` is the wait before
|
||||
the NEXT press, and is zero for the last one because the pause after a
|
||||
click belongs to whatever happens next.
|
||||
|
||||
⛔ SAME SHAPE AS `plan_typing`, AND FOR THE SAME REASON. A press with no
|
||||
duration is a press no hand made, whether it is a finger on a key or a
|
||||
finger on a button: `mouseup.timeStamp - mousedown.timeStamp` came back as
|
||||
the cost of one protocol round trip. The double click had the matching
|
||||
defect one level up - two presses with nothing between them, delivered as a
|
||||
`dblclick` anyway because the event is born from `clickCount` rather than
|
||||
from the interval, so the page saw a double click no operating system would
|
||||
have accepted as one.
|
||||
"""
|
||||
r = _rng(persona.seed, "click", nonce)
|
||||
out: List[Tuple[float, float]] = []
|
||||
for i in range(max(1, clicks)):
|
||||
dwell = _log_normal(r, persona.click_dwell_median_ms,
|
||||
persona.click_dwell_sigma)
|
||||
gap = (0.0 if i == clicks - 1
|
||||
else _log_normal(r, persona.dblclick_gap_median_ms, 0.30))
|
||||
out.append((dwell, gap))
|
||||
return out
|
||||
|
||||
|
||||
def plan_typing(text: str, persona: TypingPersona,
|
||||
nonce: int = 0) -> List[Tuple[float, float]]:
|
||||
"""One `(dwell_ms, gap_ms)` per character of `text`.
|
||||
|
||||
`dwell_ms` is how long that key stays down; `gap_ms` is the wait before the
|
||||
NEXT key goes down, and is zero for the last character because the pause
|
||||
after the last keystroke belongs to whatever happens next, not to typing.
|
||||
|
||||
⛔ THE PLAN IS COMPUTED WHERE THE SEED IS, which is here, and carried to the
|
||||
engine with the text. The engine holds no seed and decides no timing: it
|
||||
obeys. That is the same division the cursor already uses, and it is what
|
||||
keeps one session's rhythm from being a property of the machine.
|
||||
"""
|
||||
r = _rng(persona.seed, "typing", nonce)
|
||||
out: List[Tuple[float, float]] = []
|
||||
for i, ch in enumerate(text):
|
||||
dwell = _log_normal(r, persona.dwell_median_ms, persona.dwell_sigma)
|
||||
if i == len(text) - 1:
|
||||
out.append((dwell, 0.0))
|
||||
break
|
||||
nxt = text[i + 1]
|
||||
gap = _log_normal(r, persona.gap_median_ms, persona.gap_sigma)
|
||||
if ch == nxt:
|
||||
gap *= persona.same_key_factor
|
||||
else:
|
||||
a, b = _hand(ch), _hand(nxt)
|
||||
if a != "?" and b != "?":
|
||||
gap *= (persona.alternate_hand_factor if a != b
|
||||
else persona.same_hand_factor)
|
||||
if r.random() < persona.hesitation_rate:
|
||||
gap += _log_normal(r, persona.hesitation_median_ms, 0.55)
|
||||
out.append((dwell, gap))
|
||||
return out
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────
|
||||
# Movement primitives
|
||||
# ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -117,14 +117,18 @@ import asyncio
|
||||
import inspect
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
from . import _behaviour
|
||||
from . import _behaviour, _pacing
|
||||
from ._pacing import (
|
||||
DONE, SLEEP, Ev as _Ev, clamp_to_viewport as _clamp,
|
||||
fine_timer as _fine_timer,
|
||||
fit_timeline as _fit_timeline,
|
||||
)
|
||||
|
||||
# The escape hatch. ``INVPW_CURSOR_ENGINE`` picks who generates the motion:
|
||||
# "python" (default) - this module, seeded from the session seed
|
||||
@@ -241,11 +245,10 @@ else:
|
||||
#: physical fact is the shape this project keeps finding, and the looser one
|
||||
#: silently won wherever it happened to be applied last.
|
||||
#:
|
||||
#: The fallback is only reached when _motion failed to import, in which case
|
||||
#: the session is already falling back to the browser's own expansion; keeping
|
||||
#: a floor here rather than None means _fit_timeline still refuses to emit a
|
||||
#: rate no device produces.
|
||||
MIN_EVENT_INTERVAL_MS = float(getattr(_motion_mod, "SAMPLE_FLOOR_MS", 8.0)) if _motion_mod is not None else 8.0
|
||||
#: It moved into _pacing on 2026-09-16, with the discipline that reads it, so
|
||||
#: the server's drag obeys the same floor as the client's cursor. Re-exported
|
||||
#: here because it is part of this module's published surface.
|
||||
MIN_EVENT_INTERVAL_MS = _pacing.MIN_EVENT_INTERVAL_MS
|
||||
|
||||
|
||||
_MOTION_FACTORY_NAMES = ("CursorMotion", "MotionProfile", "new_motion")
|
||||
@@ -327,19 +330,6 @@ def max_seconds_for(humanize: Any) -> float:
|
||||
return value if value > 0 else _DEFAULT_MAX_SECONDS
|
||||
|
||||
|
||||
def humanize_prefs(engine: str, humanize: Any) -> dict:
|
||||
"""The browser prefs implied by the chosen engine.
|
||||
|
||||
One definition for both the sync and the async launcher, because getting
|
||||
this wrong in one of them is a silent double expansion: the wrapper draws a
|
||||
path, and the browser then draws a path between each pair of our waypoints.
|
||||
"""
|
||||
prefs: dict = {"stealthfox.humanize": engine == ENGINE_BINARY}
|
||||
if engine == ENGINE_BINARY:
|
||||
prefs["stealthfox.humanize.maxTime"] = str(max_seconds_for(humanize))
|
||||
return prefs
|
||||
|
||||
|
||||
def landing_enabled() -> bool:
|
||||
"""Whether an action may be told to click somewhere other than the centre."""
|
||||
return (os.environ.get(LANDING_ENV) or "").strip().lower() not in (
|
||||
@@ -369,66 +359,6 @@ class _RealTimer:
|
||||
|
||||
_TIMER: Any = _RealTimer()
|
||||
|
||||
# Windows quantises a waited-on timer to the system tick, which is 15.6 ms by
|
||||
# default: a 12 ms sleep comes back at 16.7 ms (measured, p50), and there is no
|
||||
# scheduling policy that can recover a resolution the platform will not give.
|
||||
# Asking for a 1 ms period brings the same sleep back at 12.5 ms. It is
|
||||
# reference-counted by the OS and released as soon as the movement is over, and
|
||||
# it is the difference between dispatching the plan and dispatching a rounded
|
||||
# copy of it - which matters here because per-seed differentiation is carried
|
||||
# largely by timing.
|
||||
TIMER_ENV = "INVPW_CURSOR_TIMER"
|
||||
|
||||
_timer_period_depth = 0
|
||||
_winmm: Any = None
|
||||
_winmm_tried = False
|
||||
|
||||
|
||||
def _timer_resolution_available() -> Any:
|
||||
global _winmm, _winmm_tried
|
||||
if _winmm_tried:
|
||||
return _winmm
|
||||
_winmm_tried = True
|
||||
if (os.environ.get(TIMER_ENV) or "").strip().lower() in ("off", "0", "false"):
|
||||
return None
|
||||
if not sys.platform.startswith("win"):
|
||||
return None
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
_winmm = ctypes.WinDLL("winmm") # type: ignore[attr-defined]
|
||||
except (OSError, ImportError): # no winmm is simply a coarser clock
|
||||
_winmm = None
|
||||
return _winmm
|
||||
|
||||
|
||||
class _fine_timer:
|
||||
"""Raise the system timer resolution for the length of one burst."""
|
||||
|
||||
def __enter__(self) -> "_fine_timer":
|
||||
global _timer_period_depth
|
||||
dll = _timer_resolution_available()
|
||||
if dll is not None:
|
||||
if _timer_period_depth == 0:
|
||||
try:
|
||||
dll.timeBeginPeriod(1)
|
||||
except (OSError, AttributeError):
|
||||
return self
|
||||
_timer_period_depth += 1
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc: Any) -> None:
|
||||
global _timer_period_depth
|
||||
if _timer_period_depth <= 0:
|
||||
return
|
||||
_timer_period_depth -= 1
|
||||
if _timer_period_depth == 0 and _winmm is not None:
|
||||
try:
|
||||
_winmm.timeEndPeriod(1)
|
||||
except (OSError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
# ── per-page seeding ────────────────────────────────────────────────────────
|
||||
|
||||
def page_motion_seed(session_seed: int, ordinal: int) -> int:
|
||||
@@ -587,28 +517,6 @@ class _PageCursor:
|
||||
# stretch. Per-seed differentiation is carried largely by timing, so that
|
||||
# stretch was quietly deleting the thing the seeding is for.
|
||||
|
||||
class _Ev:
|
||||
"""One dispatchable instant."""
|
||||
|
||||
__slots__ = ("t_ms", "x", "y", "kind", "dx", "dy")
|
||||
|
||||
def __init__(self, t_ms: float, x: float, y: float, kind: str = "move",
|
||||
dx: float = 0.0, dy: float = 0.0) -> None:
|
||||
self.t_ms = float(t_ms)
|
||||
self.x = float(x)
|
||||
self.y = float(y)
|
||||
self.kind = kind
|
||||
self.dx = float(dx)
|
||||
self.dy = float(dy)
|
||||
|
||||
@property
|
||||
def is_wheel(self) -> bool:
|
||||
return self.kind == "wheel"
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debugging aid
|
||||
return "_Ev(%.1f, %.1f, %.1f, %s)" % (self.t_ms, self.x, self.y, self.kind)
|
||||
|
||||
|
||||
def _timeline(steps: Iterable[Any]) -> List[_Ev]:
|
||||
"""Turn a ``_behaviour`` Step list (relative delays) into absolute times."""
|
||||
out: List[_Ev] = []
|
||||
@@ -622,57 +530,6 @@ def _timeline(steps: Iterable[Any]) -> List[_Ev]:
|
||||
return out
|
||||
|
||||
|
||||
def _fit_timeline(evs: List[_Ev], budget_s: float) -> List[_Ev]:
|
||||
"""Fit a timeline inside ``budget_s`` and inside what hardware can report.
|
||||
|
||||
Two rules, in this order:
|
||||
|
||||
* if the plan is longer than the budget, every timestamp is scaled - the
|
||||
same movement performed faster, not a movement that stops half way;
|
||||
* events closer together than :data:`MIN_EVENT_INTERVAL_MS` are then
|
||||
DROPPED, not squeezed. Scaling alone is what produced impossible event
|
||||
rates: the waypoint count never changed, so a tighter cap simply meant
|
||||
more events per second, without limit. The last event of the timeline
|
||||
and every wheel notch survive regardless - the first is where the
|
||||
movement has to end, the second carries a delta that would be lost.
|
||||
"""
|
||||
if not evs:
|
||||
return []
|
||||
total = evs[-1].t_ms
|
||||
if budget_s > 0 and total > budget_s * 1000.0:
|
||||
scale = (budget_s * 1000.0) / total
|
||||
for ev in evs:
|
||||
ev.t_ms *= scale
|
||||
out: List[_Ev] = []
|
||||
last_t = -MIN_EVENT_INTERVAL_MS
|
||||
for i, ev in enumerate(evs):
|
||||
if out and not ev.is_wheel and not out[-1].is_wheel \
|
||||
and ev.t_ms == out[-1].t_ms:
|
||||
# Two positions at one instant are one sample, and the sample a
|
||||
# device reports is the newest one it has.
|
||||
out[-1] = ev
|
||||
continue
|
||||
is_last = i == len(evs) - 1
|
||||
keep = (
|
||||
ev.is_wheel
|
||||
or is_last
|
||||
or ev.t_ms - last_t >= MIN_EVENT_INTERVAL_MS
|
||||
)
|
||||
if not keep:
|
||||
continue
|
||||
if is_last and out and not ev.is_wheel and not out[-1].is_wheel and ev.t_ms - last_t < MIN_EVENT_INTERVAL_MS:
|
||||
# The destination must be dispatched, so its PREDECESSOR goes
|
||||
# instead. Keeping both unconditionally is what let this function
|
||||
# emit a gap under its own floor - measured at 1.83 ms, 547 Hz,
|
||||
# with a tight time cap. A movement that stops one sample short of
|
||||
# where it was asked to go is a worse defect than one sample fewer.
|
||||
out.pop()
|
||||
last_t = out[-1].t_ms if out else -MIN_EVENT_INTERVAL_MS
|
||||
out.append(ev)
|
||||
last_t = ev.t_ms
|
||||
return out
|
||||
|
||||
|
||||
def _normalise_waypoints(raw: Iterable[Any], max_seconds: float) -> List[Tuple[float, float, float]]:
|
||||
"""Reduce whatever the generator returns to ``(x, y, delay_seconds)``.
|
||||
|
||||
@@ -731,63 +588,35 @@ async def _dispatch(
|
||||
timer: Any = None,
|
||||
emit_last: bool = True,
|
||||
) -> int:
|
||||
"""Walk a timeline against ABSOLUTE deadlines. Returns events delivered.
|
||||
"""The ASYNCHRONOUS driver of :class:`._pacing.Pacer`. Returns events sent.
|
||||
|
||||
Every deadline is measured from one ``t0``, so oversleeping on one event
|
||||
does not push the next one out: lateness cannot accumulate.
|
||||
|
||||
When the platform cannot deliver an event on time - Windows quantises a
|
||||
short sleep to the system timer, so a 12 ms request routinely returns after
|
||||
16 - the event is DROPPED rather than sent late. The rule is
|
||||
parameter-free: an event is skipped when the NEXT event is already due,
|
||||
because sending it then would be sending two events at one instant and
|
||||
would push the whole rest of the movement backwards. What survives is a
|
||||
stream whose timestamps still land where the plan put them, at whatever
|
||||
density the machine can actually produce.
|
||||
|
||||
The last event is never dropped (it is where the movement ends) and neither
|
||||
is a wheel notch (it carries a delta nobody else will send).
|
||||
The rules it obeys - absolute deadlines from one ``t0``, drop rather than
|
||||
send late, never two events in one instant - are not written here: they are
|
||||
in :mod:`._pacing`, because the server's drag is synchronous and has to obey
|
||||
the same ones. This function supplies a clock and a way of waiting; it makes
|
||||
no decision the pacer has not already made.
|
||||
"""
|
||||
tm = timer if timer is not None else _TIMER
|
||||
if not evs:
|
||||
return 0
|
||||
min_gap = MIN_EVENT_INTERVAL_MS / 1000.0
|
||||
delivered = 0
|
||||
n = len(evs)
|
||||
pacer = _pacing.Pacer(evs, emit_last=emit_last)
|
||||
with _fine_timer():
|
||||
t0 = tm.now()
|
||||
last_emit: Optional[float] = None
|
||||
for i, ev in enumerate(evs):
|
||||
last = i == n - 1
|
||||
droppable = not last and not ev.is_wheel
|
||||
deadline = t0 + ev.t_ms / 1000.0
|
||||
wait = deadline - tm.now()
|
||||
if wait > 0:
|
||||
await tm.sleep(wait)
|
||||
elif droppable and i + 1 < n:
|
||||
if tm.now() >= t0 + evs[i + 1].t_ms / 1000.0:
|
||||
continue # superseded: the next point is already due
|
||||
# Catching up after an overslept deadline must not produce two
|
||||
# events in the same instant: that is an event rate no device
|
||||
# reports, and it is as visible as being late was.
|
||||
if last_emit is not None:
|
||||
behind = min_gap - (tm.now() - last_emit)
|
||||
if behind > 0:
|
||||
if droppable:
|
||||
continue
|
||||
await tm.sleep(behind)
|
||||
if last and not emit_last:
|
||||
while True:
|
||||
what, arg = pacer.step(tm.now())
|
||||
if what == DONE:
|
||||
break
|
||||
if ev.is_wheel:
|
||||
if emit_wheel is not None:
|
||||
await emit_wheel(ev.dx, ev.dy)
|
||||
delivered += 1
|
||||
last_emit = tm.now()
|
||||
if what == SLEEP:
|
||||
await tm.sleep(arg)
|
||||
continue
|
||||
await emit_move(ev.x, ev.y)
|
||||
delivered += 1
|
||||
last_emit = tm.now()
|
||||
return delivered
|
||||
if arg.is_wheel:
|
||||
if emit_wheel is None:
|
||||
pacer.dropped() # nothing here can carry a notch
|
||||
continue
|
||||
await emit_wheel(arg.dx, arg.dy)
|
||||
else:
|
||||
await emit_move(arg.x, arg.y)
|
||||
pacer.emitted(tm.now())
|
||||
return pacer.delivered
|
||||
|
||||
|
||||
# ── registry ────────────────────────────────────────────────────────────────
|
||||
@@ -901,13 +730,6 @@ def _inside(x: float, y: float, w: Optional[float], h: Optional[float]) -> bool:
|
||||
return 0.0 <= x < float(w) and 0.0 <= y < float(h)
|
||||
|
||||
|
||||
def _clamp(x: float, y: float, w: Optional[float], h: Optional[float]) -> Tuple[float, float]:
|
||||
if not w or not h:
|
||||
return x, y
|
||||
return (
|
||||
min(max(x, 0.0), float(w) - 1.0),
|
||||
min(max(y, 0.0), float(h) - 1.0),
|
||||
)
|
||||
|
||||
|
||||
# The errors a page can legitimately produce while we are only *aiming*: the
|
||||
@@ -1252,6 +1074,13 @@ async def _approach(frame: Any, args: Sequence[Any], kwargs: dict,
|
||||
"""
|
||||
# A trial run performs the actionability checks without touching anything,
|
||||
# so it must not move a real cursor either.
|
||||
#
|
||||
# ⛔ AND THIS IS NOT WHERE `trial` IS HONOURED, which matters because for a
|
||||
# long time it was the only place that read the word at all. The action
|
||||
# itself ran regardless, so skipping the approach here made the outcome
|
||||
# WORSE: the click still went out, now with no pointer movement in front of
|
||||
# it. It is honoured in `Actions._retry`, where actionability lives; this
|
||||
# line only keeps the cursor still while that happens.
|
||||
if kwargs.get("trial"):
|
||||
return None
|
||||
page = _page_of_frame(frame)
|
||||
@@ -1607,7 +1436,6 @@ __all__ = [
|
||||
"LANDING_ENV",
|
||||
"MIN_EVENT_INTERVAL_MS",
|
||||
"enable_for",
|
||||
"humanize_prefs",
|
||||
"landing_enabled",
|
||||
"max_seconds_for",
|
||||
"motion_available",
|
||||
|
||||
@@ -18,7 +18,7 @@ import json
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
def _as_callable(expression: str) -> str:
|
||||
def _as_callable(expression: str, argument: Any) -> str:
|
||||
"""Wrap an expression so it can always be CALLED with the argument.
|
||||
|
||||
<M> PLAYWRIGHT SENDS BOTH FORMS DOWN THE SAME FIELD. `page.evaluate("1+1")`
|
||||
@@ -35,9 +35,27 @@ def _as_callable(expression: str) -> str:
|
||||
function. Deciding by shape - does it start with `(` or `function` or
|
||||
`async` - is the version that gets it wrong: `(1+2)` starts with a
|
||||
parenthesis and is not a function.
|
||||
|
||||
<M> THE ARGUMENT GOES IN HERE, IN THE SAME PASS, AND THAT IS THE WHOLE
|
||||
POINT. It used to be spelled `r(ARG)` and the caller substituted it
|
||||
afterwards with `.replace("ARG", ...)` - over a string that already held
|
||||
the caller's expression. So every uppercase `ARG` a caller wrote was
|
||||
rewritten to the argument's JSON, inside their own code, silently.
|
||||
|
||||
Measured on 2026-09-14 by driving it: `'CARGO'.length` answered 6 instead
|
||||
of 5, because the source that ran was `'CnullO'.length`; a selector
|
||||
`[data-role='TARGET']` became `[data-role='TnullET']` and matched nothing;
|
||||
`/ARGH/` became `/nullH/`; and `const ARG = 5` was a SyntaxError. The three
|
||||
letters need only appear inside a longer word - MARGIN, LARGE, CHARGE - and
|
||||
three of those four failures are silent, which is the bad kind.
|
||||
|
||||
A format string is only scanned where the format string itself is, so the
|
||||
expression is an ARGUMENT to `%` and never a place `%` looks. The sibling
|
||||
wrapper in `op_eval_on_selector` was already written this way.
|
||||
"""
|
||||
return ("(() => { const r = (%s);"
|
||||
" return typeof r === 'function' ? r(ARG) : r; })()" % expression)
|
||||
" return typeof r === 'function' ? r(%s) : r; })()"
|
||||
% (expression, json.dumps(argument, default=str)))
|
||||
|
||||
|
||||
def _deserialize(value: Any) -> Any:
|
||||
@@ -62,10 +80,13 @@ def _deserialize(value: Any) -> Any:
|
||||
|
||||
|
||||
def _with_argument(params: Dict) -> str:
|
||||
"""The expression, callable, with the caller's argument substituted in."""
|
||||
argument = _deserialize(params.get("arg"))
|
||||
return _as_callable(params["expression"]).replace(
|
||||
"ARG", json.dumps(argument, default=str))
|
||||
"""The expression, callable, with the caller's argument placed in it.
|
||||
|
||||
<M> THE ONLY PLACE THAT BUILDS THIS. `wait_for_function` used to repeat the
|
||||
two lines inline, which is how one of the two could have been fixed and the
|
||||
other left alone.
|
||||
"""
|
||||
return _as_callable(params["expression"], _deserialize(params.get("arg")))
|
||||
|
||||
|
||||
def _js_string(value: str) -> str:
|
||||
|
||||
@@ -29,6 +29,7 @@ from __future__ import annotations
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from .. import _pacing
|
||||
from .injected import EvaluationError
|
||||
from .keyboard import BUTTON_MASK, Keyboard, UnknownKey
|
||||
|
||||
@@ -79,40 +80,85 @@ def _normalize_options(options) -> list:
|
||||
|
||||
|
||||
class Actions:
|
||||
def __init__(self, connection, session: str, lifecycle, injected):
|
||||
def __init__(self, connection, session: str, lifecycle, injected,
|
||||
session_seed=None, motion_budget_s=None):
|
||||
self.c = connection
|
||||
self.session = session
|
||||
self.lifecycle = lifecycle
|
||||
self.inj = injected
|
||||
#: ⛔ THE SEED ARRIVES AND THE PERSONAE ARE BUILT HERE, rather than one
|
||||
#: ready-made object arriving per rhythm. Two of them already want the
|
||||
#: same seed - the keyboard and the pointer - and a transport carrying
|
||||
#: built objects would grow a field per rhythm while the thing that is
|
||||
#: actually session-scoped stayed the same one number.
|
||||
#:
|
||||
#: `None` throughout means humanising is off, which has to keep meaning
|
||||
#: what it meant: no rhythm, not a default one.
|
||||
self.session_seed = session_seed
|
||||
self.pointer_persona = None
|
||||
typing_persona = None
|
||||
#: ⛔ THE ONE POINTER PATH THE CLIENT CANNOT DRAW. The client's cursor
|
||||
#: wrapper does "approach THEN act", which is every action except the
|
||||
#: drag: there the movement IS the action, it happens with the button
|
||||
#: already down, and the far end is only resolved after the press. So
|
||||
#: this side needs a generator of its own - the same generator, on its
|
||||
#: own stream, because two streams that produced the same path would be
|
||||
#: a repetition a page can read.
|
||||
self.motion = None
|
||||
self.motion_budget_s = motion_budget_s
|
||||
if session_seed is not None:
|
||||
from .._behaviour import PointerPersona, TypingPersona, _sub_seed
|
||||
self.pointer_persona = PointerPersona.from_seed(session_seed)
|
||||
typing_persona = TypingPersona.from_seed(session_seed)
|
||||
try:
|
||||
from .._motion import CursorMotion
|
||||
except Exception: # noqa: BLE001 - see `_cursor`: motion is optional
|
||||
CursorMotion = None # type: ignore[assignment]
|
||||
if CursorMotion is not None:
|
||||
self.motion = CursorMotion(_sub_seed(session_seed, "server:drag"))
|
||||
#: One stream per Actions, so two clicks in a session do not repeat the
|
||||
#: same durations - the same reason the keyboard keeps one.
|
||||
self._click_nonce = 0
|
||||
#: ⛔ A SINGLE keyboard per page, and that's the point: it holds
|
||||
#: the state of the modifiers. Building one per action would lose
|
||||
#: "Shift is down" between a `down` and the next key, and
|
||||
#: `Shift+a` would type `a`.
|
||||
self.keyboard = Keyboard(connection, session)
|
||||
self.keyboard = Keyboard(connection, session, typing_persona)
|
||||
#: The last pointer position. Used by the wheel and by drag and
|
||||
#: drop, which start from where the mouse IS - not from 0,0.
|
||||
self.position = (0.0, 0.0)
|
||||
|
||||
# ── geometry ────────────────────────────────────────────────────────────
|
||||
def _in_viewport(self, point) -> bool:
|
||||
"""Is this main-frame point somewhere an event can actually land?
|
||||
def _viewport(self):
|
||||
"""The main frame's viewport, or ``(None, None)`` when it cannot be read.
|
||||
|
||||
⛔ Asked of the PAGE, not of a stored viewport size. The window can be
|
||||
resized, and a value cached at launch is a second source for a fact the
|
||||
page already knows.
|
||||
|
||||
⛔ And ONE reader for two callers, since 2026-09-16. `_in_viewport`
|
||||
asked this question already; the drag's path needs the same answer to
|
||||
keep its waypoints somewhere an event can land. Asking twice in two
|
||||
shapes is how the two would come to disagree.
|
||||
"""
|
||||
try:
|
||||
size = self.inj.evaluate(
|
||||
self.lifecycle.main_frame,
|
||||
"({w: window.innerWidth, h: window.innerHeight})")
|
||||
except Exception:
|
||||
# ⛔ Unknown is not "outside": answering False here would scroll
|
||||
# on every action the moment this probe broke.
|
||||
return True
|
||||
return None, None
|
||||
if not isinstance(size, dict):
|
||||
return None, None
|
||||
return size.get("w"), size.get("h")
|
||||
|
||||
def _in_viewport(self, point) -> bool:
|
||||
"""Is this main-frame point somewhere an event can actually land?"""
|
||||
w, h = self._viewport()
|
||||
# ⛔ Unknown is not "outside": answering False here would scroll on
|
||||
# every action the moment this probe broke.
|
||||
if w is None or h is None:
|
||||
return True
|
||||
return (0 <= point[0] <= size.get("w", 0)
|
||||
and 0 <= point[1] <= size.get("h", 0))
|
||||
return 0 <= point[0] <= w and 0 <= point[1] <= h
|
||||
|
||||
def _center_point(self, frame_id: str, element: str, position=None):
|
||||
"""Where the event lands: the quad's centre, or the caller's offset.
|
||||
@@ -156,7 +202,9 @@ class Actions:
|
||||
# ── the loop ────────────────────────────────────────────────────────────
|
||||
def _retry(self, selector: str, run, *, states=None,
|
||||
timeout: float = 30.0, frame_id: Optional[str] = None,
|
||||
position=None, element_id: Optional[str] = None):
|
||||
position=None, element_id: Optional[str] = None,
|
||||
trial: bool = False, strict: bool = False,
|
||||
force: bool = False):
|
||||
"""Resolve, check, act, and if something doesn't match, START OVER.
|
||||
|
||||
⛔ `position` travels HERE and not through each action, because the
|
||||
@@ -194,11 +242,18 @@ class Actions:
|
||||
else:
|
||||
# ⛔ FROM SCRATCH on every turn. A handle from the previous
|
||||
# turn could point to a node the DOM has since replaced.
|
||||
element = self.inj.query_selector(f, selector)
|
||||
# ⛔ `strict` REACHES HERE OR IT MEANS NOTHING. The
|
||||
# injected script has always known how to raise on it and
|
||||
# the chain accepts it, but no caller ever passed it: the
|
||||
# default stayed false, so a selector matching MORE THAN
|
||||
# ONE element acted on the FIRST instead of refusing. That
|
||||
# is not only correctness - the automation was touching an
|
||||
# element nobody had chosen.
|
||||
element = self.inj.query_selector(f, selector, strict=strict)
|
||||
ours = True
|
||||
if not element:
|
||||
reason = "the selector finds nothing"
|
||||
elif states:
|
||||
elif states and not force:
|
||||
result = self.inj.element_states(f, element, states)
|
||||
if not result.get("ok"):
|
||||
reason = "missing %s" % result.get("missing",
|
||||
@@ -228,6 +283,39 @@ class Actions:
|
||||
point = self._center_point(f, element, position)
|
||||
if point is None:
|
||||
reason = "the element has no quad (it isn't visible)"
|
||||
elif trial:
|
||||
# ⛔ TRIAL STOPS HERE, AND HERE IS THE ONLY PLACE IT CAN.
|
||||
#
|
||||
# It used to stop nowhere. The public API accepts it on
|
||||
# 31 signatures and `_juggler/` never mentioned it, so
|
||||
# `click(trial=True)` performed a real click. The only
|
||||
# reader was the cursor wrapper, which took it as a
|
||||
# reason to skip the approach and then ran the action
|
||||
# anyway: the worst of the three possible behaviours,
|
||||
# because the click went out in the most recognisable
|
||||
# form there is, with no pointer movement before it.
|
||||
#
|
||||
# This loop is where it belongs. `trial` is a statement
|
||||
# ABOUT ACTIONABILITY - run the checks, skip the act -
|
||||
# and this loop is the only thing that knows what
|
||||
# actionable means. Honouring it inside each action
|
||||
# would be the same sentence written six times, and the
|
||||
# seventh action would be written without it.
|
||||
#
|
||||
# The hit target is checked too: a trial that answers
|
||||
# yes, followed by a click that lands elsewhere, has
|
||||
# told the caller nothing. It costs one pure read.
|
||||
#
|
||||
# ⛔ Unless `force`, which skips that check on the real
|
||||
# path: a trial has to answer the question the caller
|
||||
# would actually ask, and `trial=True, force=True` asks
|
||||
# whether a FORCED action would go through.
|
||||
if not force:
|
||||
verdict = self.inj.check_hit_target(
|
||||
f, element, self._hit_point(f, point))
|
||||
if verdict != "done":
|
||||
raise WrongHitTarget(verdict)
|
||||
return None
|
||||
else:
|
||||
return run(f, element, point)
|
||||
except EvaluationError as e:
|
||||
@@ -258,66 +346,70 @@ class Actions:
|
||||
time.sleep(0.05)
|
||||
|
||||
# ── the hit target ──────────────────────────────────────────────────────
|
||||
def _with_hit_target(self, f, element, point, kind, act):
|
||||
"""Acts ONLY if the event truly lands on the intended element.
|
||||
def _hit_point(self, f, point):
|
||||
"""The caller's point, expressed in `f`'s own coordinate space.
|
||||
|
||||
⛔ This is NOT one more check before acting: it's an interceptor
|
||||
installed FOR THE WHOLE DURATION of the action. The difference
|
||||
matters, because a check beforehand leaves open exactly the window
|
||||
this closes - the page can move between the check and the event.
|
||||
Here the listener watches the event WHILE it arrives, and if the
|
||||
point doesn't belong to the intended element it BLOCKS it and says
|
||||
so.
|
||||
⛔ A POINT IS ALWAYS IN THE MAIN FRAME'S SPACE when it gets here:
|
||||
`Page.getContentQuads` answers there and `dispatchMouseEvent` wants it
|
||||
there. Handing that number to a hit test running INSIDE a nested frame
|
||||
asks the child about a coordinate that means something else, and it
|
||||
answers `<html>` - which is how a covered element used to be reported
|
||||
for something sitting right under the pointer.
|
||||
|
||||
It's the driver's own mechanism (`setupHitTargetInterceptor`), so
|
||||
it adds no new surface: the listeners that serve it are already
|
||||
installed, **in the utility world** after the fix in
|
||||
`31-client-fork.md` §3.9. In the page world they would be
|
||||
countable.
|
||||
The shift is the difference between the two content origins, read from
|
||||
the engine rather than recomputed here.
|
||||
"""
|
||||
# ⛔ THE PRELIMINARY POINT ONLY IN THE MAIN FRAME, and the reason is a
|
||||
# coordinate space, not a preference. `Page.getContentQuads` answers in
|
||||
# the MAIN frame's space - `getBoxQuads({relativeTo: mainFrame})`, read
|
||||
# in `PageAgent.js` - which is exactly what `dispatchMouseEvent` wants.
|
||||
# But the interceptor runs inside the TARGET frame's document, and its
|
||||
# preliminary `expectHitTarget(hitPoint, el)` calls `elementFromPoint`
|
||||
# THERE. Handing it a main-frame point inside a nested iframe asks the
|
||||
# child about a coordinate that means something else, and it answers
|
||||
# `<html>` - measured as `the event would have landed elsewhere` on an
|
||||
# element that was sitting right under the pointer.
|
||||
#
|
||||
# Passing null skips only the check BEFORE the event. The listener
|
||||
# still validates each event as it arrives, using the event's OWN
|
||||
# clientX/clientY, which are already in the right document. The
|
||||
# guarantee is unchanged; a covered element in a child frame is caught
|
||||
# at dispatch time instead of a moment earlier.
|
||||
in_main = f == self.lifecycle.main_frame
|
||||
h = self.inj.call(
|
||||
f,
|
||||
"(injected, el, a, p) => {"
|
||||
" const r = injected.setupHitTargetInterceptor(el, a, p, false);"
|
||||
" return typeof r === 'string' ? {error: r} : {stop: r.stop}; }",
|
||||
{"objectId": element}, kind,
|
||||
{"x": point[0], "y": point[1]} if in_main else None,
|
||||
by_value=False)
|
||||
try:
|
||||
failure = self.inj.call(f, "(injected, h) => h.error || ''",
|
||||
{"objectId": h})
|
||||
if failure:
|
||||
raise WrongHitTarget(failure)
|
||||
result = act()
|
||||
# ⛔ `stop()` returns `"done"` OR an object describing what was
|
||||
# actually hit. Reading it as a boolean would always say yes,
|
||||
# which is the same defect as `elementState`.
|
||||
done = self.inj.call(
|
||||
f, "(injected, h) => { const r = h.stop ? h.stop() : 'done';"
|
||||
" return typeof r === 'string' ? r : JSON.stringify(r); }",
|
||||
{"objectId": h})
|
||||
if done != "done":
|
||||
raise WrongHitTarget(done)
|
||||
return result
|
||||
finally:
|
||||
self.inj.dispose(f, h)
|
||||
if f == self.lifecycle.main_frame:
|
||||
return point
|
||||
main = self.inj.content_origin(self.lifecycle.main_frame)
|
||||
here = self.inj.content_origin(f)
|
||||
return (point[0] + main["x"] - here["x"],
|
||||
point[1] + main["y"] - here["y"])
|
||||
|
||||
def _with_hit_target(self, f, element, point, act, *, force: bool = False):
|
||||
"""Acts only if the point belongs to the intended element, and says so
|
||||
again afterwards.
|
||||
|
||||
⛔ `force` SKIPS IT, AND THAT IS NOT AN EXEMPTION - IT IS WHAT THE
|
||||
OPTION MEANS. "Receives events" is one of the actionability checks
|
||||
`force` is documented to bypass, and an overlay intercepting the
|
||||
pointer is the ordinary reason somebody passes it. Honouring `force`
|
||||
on the state checks alone would leave it half wired, which is the
|
||||
defect this was: an option accepted on every public signature that
|
||||
changed nothing a caller could observe.
|
||||
|
||||
⛔ IT USED TO BE AN INTERCEPTOR, and the difference is the point of
|
||||
this function. An interceptor watched the event WHILE it arrived and
|
||||
BLOCKED it when the point had stopped belonging to the element. That
|
||||
closed the race between the check and the event - and it cost two things
|
||||
that were worse than the race.
|
||||
|
||||
It needed capture listeners on the PAGE's window for the duration of
|
||||
every action, the last thing this package left there. And the block
|
||||
itself was the tell: a real `mousedown` that vanishes under
|
||||
`preventDefault` is not something any input stack produces, so the
|
||||
defence announced us exactly when it worked.
|
||||
|
||||
Two pure reads instead. The one BEFORE refuses to act on a point that
|
||||
has already stopped belonging to the element; the one AFTER catches the
|
||||
target that moved in between and turns it into a retry. What a page sees
|
||||
in that case is a click that landed where the thing it was aimed at used
|
||||
to be, which is what a hand produces when a layout shifts under it.
|
||||
|
||||
Measured by `tests/gates/injected_page_surface.js`: the bundle now
|
||||
touches the page's window zero times, in every phase.
|
||||
"""
|
||||
if force:
|
||||
return act()
|
||||
here = self._hit_point(f, point)
|
||||
before = self.inj.check_hit_target(f, element, here)
|
||||
if before != "done":
|
||||
raise WrongHitTarget(before)
|
||||
result = act()
|
||||
after = self.inj.check_hit_target(f, element, here)
|
||||
if after != "done":
|
||||
raise WrongHitTarget(after)
|
||||
return result
|
||||
|
||||
# ── waiting ─────────────────────────────────────────────────────────────
|
||||
def wait_for_selector(self, selector: str, *, state: str = "visible",
|
||||
@@ -368,16 +460,19 @@ class Actions:
|
||||
|
||||
# ── the actions ─────────────────────────────────────────────────────────
|
||||
def hover(self, selector: str, *, timeout: float = 30.0, frame_id: Optional[str] = None,
|
||||
position=None, element_id: Optional[str] = None):
|
||||
position=None, element_id: Optional[str] = None, **opts):
|
||||
def run(f, element, point):
|
||||
return self._with_hit_target(
|
||||
f, element, point, "hover",
|
||||
lambda: self._mouse_event("mousemove", point) or point)
|
||||
f, element, point,
|
||||
lambda: self._mouse_event("mousemove", point) or point,
|
||||
force=bool(opts.get("force")))
|
||||
return self._retry(selector, run, timeout=timeout, element_id=element_id,
|
||||
frame_id=frame_id, position=position)
|
||||
frame_id=frame_id, position=position, **opts)
|
||||
|
||||
def click(self, selector: str, *, timeout: float = 30.0, frame_id: Optional[str] = None, button: int = 0,
|
||||
clicks: int = 1, position=None, modifiers: int = 0, element_id: Optional[str] = None):
|
||||
delay_ms: Optional[float] = None,
|
||||
clicks: int = 1, position=None, modifiers: int = 0,
|
||||
element_id: Optional[str] = None, **opts):
|
||||
def run(f, element, point):
|
||||
def act():
|
||||
# The order is that of a user: approach, press, release.
|
||||
@@ -390,14 +485,16 @@ class Actions:
|
||||
# which no real input device produces.
|
||||
self._mouse_event("mousemove", point, modifiers=modifiers)
|
||||
self._click_at_point(point, button=button, clicks=clicks,
|
||||
modifiers=modifiers)
|
||||
modifiers=modifiers, delay_ms=delay_ms)
|
||||
return point
|
||||
return self._with_hit_target(f, element, point, "mouse", act)
|
||||
return self._with_hit_target(f, element, point, act,
|
||||
force=bool(opts.get("force")))
|
||||
return self._retry(selector, run, timeout=timeout, frame_id=frame_id,
|
||||
position=position, element_id=element_id)
|
||||
position=position, element_id=element_id, **opts)
|
||||
|
||||
def dblclick(self, selector: str, *, timeout: float = 30.0, frame_id: Optional[str] = None,
|
||||
button: int = 0, position=None, modifiers: int = 0):
|
||||
delay_ms: Optional[float] = None,
|
||||
button: int = 0, position=None, modifiers: int = 0, **opts):
|
||||
"""⛔ These are NOT two `click`s in a row: the second one must carry
|
||||
`clickCount: 2`, and it's that field - not the interval between the
|
||||
two - that gives birth to the `dblclick` event. Two clicks with
|
||||
@@ -412,20 +509,21 @@ class Actions:
|
||||
argument was honoured; nothing else did."""
|
||||
return self.click(selector, timeout=timeout, button=button,
|
||||
clicks=2, frame_id=frame_id, position=position,
|
||||
modifiers=modifiers)
|
||||
modifiers=modifiers, delay_ms=delay_ms, **opts)
|
||||
|
||||
def check(self, selector: str, *, timeout: float = 30.0, frame_id: Optional[str] = None,
|
||||
position=None, element_id: Optional[str] = None):
|
||||
position=None, element_id: Optional[str] = None, **opts):
|
||||
return self._set_checked(selector, True, timeout=timeout, element_id=element_id,
|
||||
frame_id=frame_id, position=position)
|
||||
frame_id=frame_id, position=position, **opts)
|
||||
|
||||
def uncheck(self, selector: str, *, timeout: float = 30.0, frame_id: Optional[str] = None,
|
||||
position=None, element_id: Optional[str] = None):
|
||||
position=None, element_id: Optional[str] = None, **opts):
|
||||
return self._set_checked(selector, False, timeout=timeout, element_id=element_id,
|
||||
frame_id=frame_id, position=position)
|
||||
frame_id=frame_id, position=position, **opts)
|
||||
|
||||
def _set_checked(self, selector: str, wanted: bool, *, timeout: float,
|
||||
frame_id: Optional[str] = None, position=None, element_id: Optional[str] = None):
|
||||
frame_id: Optional[str] = None, position=None,
|
||||
element_id: Optional[str] = None, **opts):
|
||||
"""`check` / `uncheck`.
|
||||
|
||||
⛔ It CHECKS FIRST, and rechecks after. Clicking without looking
|
||||
@@ -448,7 +546,8 @@ class Actions:
|
||||
# directly and failed on the very page that shifts its layout
|
||||
# at 1200 ms. One single place knows how to click; two know it
|
||||
# only until one of them learns something the other doesn't.
|
||||
self._with_hit_target(f, element, point, "mouse", act)
|
||||
self._with_hit_target(f, element, point, act,
|
||||
force=bool(opts.get("force")))
|
||||
if not self.inj.element_state(f, element, state):
|
||||
raise EvaluationError(
|
||||
"clicked but the box stayed %s: someone intercepted "
|
||||
@@ -456,9 +555,11 @@ class Actions:
|
||||
% ("unchecked" if wanted else "checked"))
|
||||
return state
|
||||
return self._retry(selector, run, timeout=timeout, element_id=element_id,
|
||||
frame_id=frame_id, position=position)
|
||||
frame_id=frame_id, position=position, **opts)
|
||||
|
||||
def focus(self, selector: str, *, timeout: float = 30.0, frame_id: Optional[str] = None, element_id: Optional[str] = None):
|
||||
def focus(self, selector: str, *, timeout: float = 30.0,
|
||||
frame_id: Optional[str] = None,
|
||||
element_id: Optional[str] = None, **opts):
|
||||
"""⛔ Does NOT require `visible`: `focus()` works on an off-screen
|
||||
element, and imposing the pointer states would time out an action
|
||||
that would have succeeded. Playwright does the same."""
|
||||
@@ -467,9 +568,10 @@ class Actions:
|
||||
f, "(injected, el) => injected.focusNode(el, true)",
|
||||
{"objectId": element})
|
||||
return self._retry(selector, run, states=[], timeout=timeout, frame_id=frame_id,
|
||||
element_id=element_id)
|
||||
element_id=element_id, **opts)
|
||||
|
||||
def blur(self, selector: str, *, timeout: float = 30.0, frame_id: Optional[str] = None):
|
||||
def blur(self, selector: str, *, timeout: float = 30.0,
|
||||
frame_id: Optional[str] = None, **opts):
|
||||
def run(f, element, point):
|
||||
return self.inj.call(
|
||||
f,
|
||||
@@ -477,9 +579,10 @@ class Actions:
|
||||
"'error:notconnected'; el.blur(); return 'done'; }",
|
||||
{"objectId": element})
|
||||
return self._retry(selector, run, states=[], timeout=timeout, frame_id=frame_id,
|
||||
)
|
||||
**opts)
|
||||
|
||||
def select_text(self, selector: str, *, timeout: float = 30.0, frame_id: Optional[str] = None):
|
||||
def select_text(self, selector: str, *, timeout: float = 30.0,
|
||||
frame_id: Optional[str] = None, **opts):
|
||||
def run(f, element, point):
|
||||
r = self.inj.call(f, "(injected, el) => injected.selectText(el)",
|
||||
{"objectId": element})
|
||||
@@ -487,9 +590,11 @@ class Actions:
|
||||
raise EvaluationError("selectText: %s" % r)
|
||||
return r
|
||||
return self._retry(selector, run, states=["visible"],
|
||||
timeout=timeout, frame_id=frame_id)
|
||||
timeout=timeout, frame_id=frame_id, **opts)
|
||||
|
||||
def select_option(self, selector: str, options, *, timeout: float = 30.0, frame_id: Optional[str] = None, element_id: Optional[str] = None):
|
||||
def select_option(self, selector: str, options, *, timeout: float = 30.0,
|
||||
frame_id: Optional[str] = None,
|
||||
element_id: Optional[str] = None, **opts):
|
||||
"""`select_option`. Options are given by value, label or index.
|
||||
|
||||
⛔ And the `input`/`change` events are requested from the TRUSTED
|
||||
@@ -511,10 +616,11 @@ class Actions:
|
||||
return self._retry(selector, run,
|
||||
states=["visible", "stable", "enabled"],
|
||||
timeout=timeout, frame_id=frame_id,
|
||||
element_id=element_id)
|
||||
element_id=element_id, **opts)
|
||||
|
||||
def dispatch_event(self, selector: str, event_type: str, detail=None, *,
|
||||
timeout: float = 30.0, frame_id: Optional[str] = None):
|
||||
timeout: float = 30.0, frame_id: Optional[str] = None,
|
||||
**opts):
|
||||
"""`dispatch_event`.
|
||||
|
||||
⛔ This is the ONLY spot in the file where an event comes out NOT
|
||||
@@ -530,9 +636,11 @@ class Actions:
|
||||
f, "(injected, el, t, d) => injected.dispatchEvent(el, t, d)",
|
||||
{"objectId": element}, event_type, detail or {})
|
||||
return self._retry(selector, run, states=[], timeout=timeout, frame_id=frame_id,
|
||||
)
|
||||
**opts)
|
||||
|
||||
def press(self, selector: str, key: str, *, timeout: float = 30.0, frame_id: Optional[str] = None, element_id: Optional[str] = None):
|
||||
def press(self, selector: str, key: str, *, timeout: float = 30.0,
|
||||
frame_id: Optional[str] = None,
|
||||
element_id: Optional[str] = None, **opts):
|
||||
"""`press`: focuses and presses, with the modifiers from the name."""
|
||||
def run(f, element, point):
|
||||
self.inj.call(f, "(injected, el) => injected.focusNode(el, true)",
|
||||
@@ -542,10 +650,11 @@ class Actions:
|
||||
return self._retry(selector, run,
|
||||
states=["visible", "stable", "enabled"],
|
||||
timeout=timeout, frame_id=frame_id,
|
||||
element_id=element_id)
|
||||
element_id=element_id, **opts)
|
||||
|
||||
def type_text(self, selector: str, text: str, *, timeout: float = 30.0, frame_id: Optional[str] = None,
|
||||
delay: float = 0.0, element_id: Optional[str] = None):
|
||||
delay: float = 0.0, element_id: Optional[str] = None,
|
||||
**opts):
|
||||
"""`type`: one key per character, WITHOUT clearing first.
|
||||
|
||||
⛔ It isn't `fill`: that one replaces the content, this one
|
||||
@@ -555,20 +664,29 @@ class Actions:
|
||||
def run(f, element, point):
|
||||
self.inj.call(f, "(injected, el) => injected.focusNode(el, true)",
|
||||
{"objectId": element})
|
||||
self.keyboard.type(text, delay=delay)
|
||||
self.keyboard.type(text, delay_ms=delay)
|
||||
return text
|
||||
return self._retry(selector, run,
|
||||
states=["visible", "stable", "enabled"],
|
||||
timeout=timeout, frame_id=frame_id,
|
||||
element_id=element_id)
|
||||
element_id=element_id, **opts)
|
||||
|
||||
def set_input_files(self, selector: str, files, *, timeout: float = 30.0, frame_id: Optional[str] = None):
|
||||
def set_input_files(self, selector: str, files, *, timeout: float = 30.0,
|
||||
frame_id: Optional[str] = None,
|
||||
element_id: Optional[str] = None, **opts):
|
||||
"""`set_input_files`. The paths are ABSOLUTE and the browser
|
||||
resolves them.
|
||||
|
||||
⛔ Goes through `Page.setFileInputFiles` and not the injected
|
||||
script: a page can't construct a `FileList`, and trying would
|
||||
leave the input empty with no error.
|
||||
|
||||
⛔ `element_id` WAS MISSING, AND THAT IS WHY A FILE CHOOSER COULD NOT
|
||||
UPLOAD ANYTHING. `FileChooser.set_files()` does not go through a
|
||||
selector - it holds the input element already - so it asks the
|
||||
ElementHandle for `setInputFiles`, and without this parameter there was
|
||||
nothing for that dispatcher to call. Every other action here takes the
|
||||
handle; this one was the exception nobody had needed yet.
|
||||
"""
|
||||
def run(f, element, point):
|
||||
self.c.send("Page.setFileInputFiles",
|
||||
@@ -576,11 +694,11 @@ class Actions:
|
||||
"files": [str(p) for p in files]},
|
||||
session=self.session, timeout=30)
|
||||
return list(files)
|
||||
return self._retry(selector, run, states=[], timeout=timeout, frame_id=frame_id,
|
||||
)
|
||||
return self._retry(selector, run, states=[], timeout=timeout,
|
||||
frame_id=frame_id, element_id=element_id, **opts)
|
||||
|
||||
def tap(self, selector: str, *, timeout: float = 30.0, frame_id: Optional[str] = None,
|
||||
position=None):
|
||||
position=None, **opts):
|
||||
"""`tap`. ⛔ Requires the context to have touch TURNED ON: without
|
||||
it, the event fires and the page has no `ontouchstart`, so it
|
||||
doesn't listen for it - it succeeds and does nothing. Touch is
|
||||
@@ -593,11 +711,56 @@ class Actions:
|
||||
session=self.session, timeout=10)
|
||||
return point
|
||||
return self._retry(selector, run, timeout=timeout,
|
||||
frame_id=frame_id, position=position)
|
||||
frame_id=frame_id, position=position, **opts)
|
||||
|
||||
def _glide(self, to_point, *, buttons: int = 0) -> int:
|
||||
"""Move the pointer to *to_point* along a path a hand could have drawn.
|
||||
|
||||
⛔ WHY THIS EXISTS ON THIS SIDE AT ALL. Every other pointer action is
|
||||
approached by the client's cursor wrapper, which walks the cursor onto
|
||||
the element BEFORE calling the action. A drag cannot be served that way:
|
||||
the travel happens with the button already down, and its far end is only
|
||||
known after the press. So the movement is generated here - from the same
|
||||
generator (`_motion.CursorMotion`) and delivered under the same
|
||||
discipline (`_pacing`) as every movement the client makes. Neither is
|
||||
reimplemented here; a second copy of either is the defect this replaced.
|
||||
|
||||
Returns the number of events actually delivered. Falls back to a single
|
||||
event when there is no generator (`humanize=False`, or a broken
|
||||
install), which is what "no humanising" has always meant here.
|
||||
"""
|
||||
if self.motion is None:
|
||||
self._mouse_event("mousemove", to_point, buttons=buttons)
|
||||
return 1
|
||||
x0, y0 = self.position
|
||||
# ⛔ `path[1:]`: a path INCLUDES where it starts, and the pointer is
|
||||
# already there. Sending it would report a move to the point the last
|
||||
# event already reported - two identical events in a row, which is the
|
||||
# very pair this replaced. The client's walk drops it for the same
|
||||
# reason; found here by the browser arm, because in isolation there is
|
||||
# no preceding event for it to duplicate.
|
||||
path = self.motion.path(x0, y0, to_point[0], to_point[1])[1:]
|
||||
# ⛔ A curved path near an edge leaves the viewport on its own, and a
|
||||
# pointer event outside it is not ignored - the browser parks the cursor
|
||||
# at the origin, mid-movement. The destination is emitted unclamped: it
|
||||
# is where the movement has to end.
|
||||
w, h = self._viewport()
|
||||
evs = [_pacing.Ev(wp.t_ms, *_pacing.clamp_to_viewport(wp.x, wp.y, w, h))
|
||||
for wp in path[:-1]]
|
||||
evs.append(_pacing.Ev(path[-1].t_ms, to_point[0], to_point[1]))
|
||||
if self.motion_budget_s:
|
||||
evs = _pacing.fit_timeline(evs, self.motion_budget_s)
|
||||
if not evs: # a generator that produced nothing must still arrive
|
||||
self._mouse_event("mousemove", to_point, buttons=buttons)
|
||||
return 1
|
||||
return _pacing.drive(
|
||||
evs, lambda x, y: self._mouse_event("mousemove", (x, y),
|
||||
buttons=buttons))
|
||||
|
||||
def drag_and_drop(self, source: str, target: str, *,
|
||||
timeout: float = 30.0,
|
||||
frame_id: Optional[str] = None):
|
||||
frame_id: Optional[str] = None,
|
||||
**opts):
|
||||
"""`drag_and_drop`, in four beats.
|
||||
|
||||
⛔ THE FIRST `mousemove` AFTER THE `mousedown` IS NOT SKIPPED.
|
||||
@@ -606,22 +769,44 @@ class Actions:
|
||||
clicks. And the two ends are resolved SEPARATELY, each with its
|
||||
own retry loop, because taking the second point before pressing
|
||||
the first would measure it on a page that is about to change.
|
||||
|
||||
⛔ AND THE TRAVEL IS A PATH, NOT A JUMP - which is a correctness fix as
|
||||
well as a stealth one. Measured 2026-09-16 on a page whose source was
|
||||
`draggable`: this used to emit five events in all, of which the two
|
||||
carrying the whole 480-pixel journey were IDENTICAL and 7 ms apart - a
|
||||
pair no device can produce, since a move event is born from moving. The
|
||||
second was there because one jump alone did not reliably start the drag.
|
||||
With a real path it is not needed: the drag is born at the first point
|
||||
that clears Gecko's threshold, the way it is for a hand.
|
||||
"""
|
||||
start = self._retry(source, lambda f, el, p: p, timeout=timeout, frame_id=frame_id)
|
||||
self._mouse_event("mousemove", start)
|
||||
if opts.get("trial"):
|
||||
# ⛔ BOTH ENDS, AND NOT ONE EVENT. A drag that only checked the
|
||||
# source would answer half the question, and the half it skipped is
|
||||
# the one that fails: a target covered by an overlay is the ordinary
|
||||
# reason a drag does not land. Resolved in order, because resolving
|
||||
# the target first would measure it on a page the press is about to
|
||||
# change - the same reason the real path resolves them separately.
|
||||
self._retry(source, lambda f, el, p: p, timeout=timeout,
|
||||
frame_id=frame_id, **opts)
|
||||
self._retry(target, lambda f, el, p: p, timeout=timeout,
|
||||
frame_id=frame_id, **opts)
|
||||
return None
|
||||
start = self._retry(source, lambda f, el, p: p, timeout=timeout,
|
||||
frame_id=frame_id, **opts)
|
||||
# The approach is a path too: the cursor was somewhere before this call,
|
||||
# and arriving at the source in one event is the same tell as crossing
|
||||
# the page in one.
|
||||
self._glide(start)
|
||||
self._mouse_event("mousedown", start, buttons=BUTTON_MASK[0],
|
||||
click_count=1)
|
||||
|
||||
def run(f, element, point):
|
||||
# Two movements: one gives birth to the drag, the second one
|
||||
# carries it onto the target. With only one, Gecko sometimes
|
||||
# doesn't start it.
|
||||
self._mouse_event("mousemove", point, buttons=BUTTON_MASK[0])
|
||||
self._mouse_event("mousemove", point, buttons=BUTTON_MASK[0])
|
||||
self._glide(point, buttons=BUTTON_MASK[0])
|
||||
self._mouse_event("mouseup", point, buttons=0, click_count=1)
|
||||
return point
|
||||
try:
|
||||
return self._retry(target, run, timeout=timeout, frame_id=frame_id)
|
||||
return self._retry(target, run, timeout=timeout, frame_id=frame_id,
|
||||
**opts)
|
||||
except BaseException:
|
||||
# ⛔ A button left down poisons EVERY subsequent action: the
|
||||
# `buttons` field of every event after would say "pressed".
|
||||
@@ -647,9 +832,10 @@ class Actions:
|
||||
buttons=0, click_count=clicks)
|
||||
|
||||
def click_at(self, x: float, y: float, *, button: int = 0,
|
||||
clicks: int = 1):
|
||||
clicks: int = 1, delay_ms: Optional[float] = None):
|
||||
self.move(x, y)
|
||||
self._click_at_point((x, y), button=button, clicks=clicks)
|
||||
self._click_at_point((x, y), button=button, clicks=clicks,
|
||||
delay_ms=delay_ms)
|
||||
|
||||
def wheel(self, dx: float, dy: float) -> None:
|
||||
"""`mouse.wheel`, from where the pointer IS - not from 0,0."""
|
||||
@@ -660,7 +846,8 @@ class Actions:
|
||||
session=self.session, timeout=10)
|
||||
|
||||
def _click_at_point(self, point, *, button: int = 0,
|
||||
clicks: int = 1, modifiers: int = 0) -> None:
|
||||
clicks: int = 1, modifiers: int = 0,
|
||||
delay_ms: Optional[float] = None) -> None:
|
||||
"""⛔ `clickCount` GROWS between hits: 1, then 2. It's that field
|
||||
that gives birth to `dblclick`, not the interval. And the
|
||||
release's `buttons` is zero, because it describes what stays
|
||||
@@ -672,14 +859,44 @@ class Actions:
|
||||
`modifiers=["Shift"]` have to reach the page identically. It used to be
|
||||
dropped entirely: `event.shiftKey` came back false on a click the
|
||||
caller had explicitly modified, with no error anywhere."""
|
||||
plan = self._click_plan(clicks, delay_ms)
|
||||
for n in range(1, clicks + 1):
|
||||
dwell_ms, gap_ms = plan[n - 1]
|
||||
self._mouse_event("mousedown", point, button=button,
|
||||
buttons=BUTTON_MASK[button], click_count=n,
|
||||
modifiers=modifiers)
|
||||
if dwell_ms > 0.0:
|
||||
time.sleep(dwell_ms / 1000.0)
|
||||
self._mouse_event("mouseup", point, button=button, buttons=0,
|
||||
click_count=n, modifiers=modifiers)
|
||||
if gap_ms > 0.0:
|
||||
time.sleep(gap_ms / 1000.0)
|
||||
|
||||
def fill(self, selector: str, text: str, *, timeout: float = 30.0, frame_id: Optional[str] = None, element_id: Optional[str] = None):
|
||||
def _click_plan(self, clicks: int, delay_ms: Optional[float] = None):
|
||||
"""How long each press lasts and how long until the next one.
|
||||
|
||||
⛔ A PRESS WITH NO DURATION IS A PRESS NO HAND MADE. `mousedown` and
|
||||
`mouseup` used to leave together, so what a page measured as the hold
|
||||
was one protocol round trip, and the two presses of a double click had
|
||||
nothing between them either - delivered as a `dblclick` regardless,
|
||||
because that event is born from `clickCount` and not from the interval,
|
||||
so a page saw a double click no operating system would have accepted.
|
||||
|
||||
⛔ `delay_ms` IS THE CALLER'S OVERRIDE and Playwright documents it in
|
||||
milliseconds - the wait between `mousedown` and `mouseup`. It used to
|
||||
be dropped here, so the only rhythm available was none.
|
||||
"""
|
||||
if delay_ms:
|
||||
return [(float(delay_ms), 0.0)] * clicks
|
||||
if self.pointer_persona is None:
|
||||
return [(0.0, 0.0)] * clicks
|
||||
from .._behaviour import plan_click
|
||||
self._click_nonce += 1
|
||||
return plan_click(self.pointer_persona, clicks, nonce=self._click_nonce)
|
||||
|
||||
def fill(self, selector: str, text: str, *, timeout: float = 30.0,
|
||||
frame_id: Optional[str] = None,
|
||||
element_id: Optional[str] = None, **opts):
|
||||
"""Writes into a field.
|
||||
|
||||
⛔ It doesn't just write `element.value = ...`: a site listening
|
||||
@@ -712,7 +929,7 @@ class Actions:
|
||||
return self._retry(selector, run, element_id=element_id,
|
||||
states=["visible", "stable", "enabled",
|
||||
"editable"],
|
||||
timeout=timeout, frame_id=frame_id)
|
||||
timeout=timeout, frame_id=frame_id, **opts)
|
||||
|
||||
# ── the tools ───────────────────────────────────────────────────────────
|
||||
def _mouse_event(self, event_type: str, point, *, button: int = 0,
|
||||
|
||||
@@ -52,6 +52,36 @@ class ProtocolError(RuntimeError):
|
||||
"""
|
||||
|
||||
|
||||
class TargetClosedError(Exception):
|
||||
"""The thing a call was aimed at is gone: a disposed object, or the
|
||||
browser itself, whose pipe has closed.
|
||||
|
||||
⛔ THE CLASS NAME IS THE CONTRACT, not decoration. `reply_error` puts
|
||||
`type(failure).__name__` in the error payload, and `_helper.parse_error`
|
||||
turns that exact string into the fork's `TargetClosedError` on the client
|
||||
- which is the ONLY thing `_page.py`'s `close()` swallows:
|
||||
|
||||
except Exception as e:
|
||||
if is_target_closed_error(e): return
|
||||
|
||||
Anything else propagates. So closing a page whose context was closed first
|
||||
- `context.close()` cascades, then a fixture teardown calls `page.close()`,
|
||||
which is an ordinary shape and not a misuse - raised a hard error here on
|
||||
2026-08-28, the day closed pages started being disposed at all.
|
||||
|
||||
⛔ AND IT LIVES HERE, ONE LAYER DOWN FROM WHERE IT WAS BORN, BECAUSE A
|
||||
CLOSED PIPE IS A CLOSED TARGET TOO. Until 0.15.0 the dispatcher raised
|
||||
this for a disposed guid, while the connection answered a pipe that had
|
||||
closed with a nameless error - `the pipe closed`, `the pipe is closed` -
|
||||
which `parse_error` turned into the fork's plain `Error`. The same fact,
|
||||
the browser is gone, reached a caller as two different classes, and the
|
||||
caller that had to tell "the page refused" from "the browser died" (the
|
||||
AIHawk server's retry) was reduced to matching the sentences. Measured
|
||||
2026-09-14. One class, raised by both layers, and exported from the
|
||||
public API so a caller can catch the TYPE.
|
||||
"""
|
||||
|
||||
|
||||
class EventListeners:
|
||||
"""Who is subscribed to a connection's events, and how one is delivered.
|
||||
|
||||
@@ -177,7 +207,10 @@ class Connection(EventListeners):
|
||||
pending = list(self._pending.values())
|
||||
self._pending.clear()
|
||||
for ready, box in pending:
|
||||
box.append({"error": {"message": "the pipe closed"}})
|
||||
# Named, so `send` raises the closed-target class and the
|
||||
# client sees the browser is GONE rather than a refusal.
|
||||
box.append({"error": {"name": "TargetClosedError",
|
||||
"message": "the pipe closed"}})
|
||||
ready.set()
|
||||
|
||||
def _deliver(self, raw: bytes) -> None:
|
||||
@@ -221,7 +254,7 @@ class Connection(EventListeners):
|
||||
def send(self, method: str, params: Optional[dict] = None,
|
||||
session: Optional[str] = None, timeout: float = 30.0) -> Any:
|
||||
if self._closed:
|
||||
raise ProtocolError("the pipe is closed: %s" % (self._error or ""))
|
||||
raise TargetClosedError("the pipe is closed: %s" % (self._error or ""))
|
||||
with self._lock:
|
||||
self._next_id += 1
|
||||
msg_id = self._next_id
|
||||
@@ -258,6 +291,8 @@ class Connection(EventListeners):
|
||||
response = box[0]
|
||||
if "error" in response:
|
||||
e = response["error"]
|
||||
if e.get("name") == "TargetClosedError":
|
||||
raise TargetClosedError("%s: %s" % (method, e.get("message", e)))
|
||||
raise ProtocolError("%s: %s" % (method, e.get("message", e)))
|
||||
return response.get("result")
|
||||
|
||||
|
||||
@@ -36,26 +36,11 @@ import threading
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
from . import perimeter
|
||||
# One class for a target that is gone, raised here for a disposed object and
|
||||
# by the connection for a closed pipe. Defined there, the lower layer.
|
||||
from .connection import TargetClosedError # noqa: F401 - re-exported on purpose
|
||||
|
||||
|
||||
class TargetClosedError(Exception):
|
||||
"""A call that arrived after its object was disposed.
|
||||
|
||||
⛔ THE CLASS NAME IS THE CONTRACT, not decoration. `reply_error` puts
|
||||
`type(failure).__name__` in the error payload, and `_helper.parse_error`
|
||||
turns that exact string into `TargetClosedError` on the client - which is
|
||||
the ONLY thing `_page.py`'s `close()` swallows:
|
||||
|
||||
except Exception as e:
|
||||
if is_target_closed_error(e): return
|
||||
|
||||
Anything else propagates. So closing a page whose context was closed first
|
||||
- `context.close()` cascades, then a fixture teardown calls `page.close()`,
|
||||
which is an ordinary shape and not a misuse - raised a hard error here on
|
||||
2026-08-28, the day closed pages started being disposed at all. Two of
|
||||
Playwright's own tests caught it; nothing of ours did, because nothing of
|
||||
ours closes a page twice.
|
||||
"""
|
||||
|
||||
|
||||
class ProtocolException(Exception):
|
||||
|
||||
@@ -6584,7 +6584,6 @@ var InjectedScript = class {
|
||||
this._testIdAttributeNameForStrictErrorAndConsoleCodegen = options.testIdAttributeName;
|
||||
this._evaluator = new SelectorEvaluatorImpl();
|
||||
this.consoleApi = new ConsoleAPI(this);
|
||||
this.onGlobalListenersRemoved = /* @__PURE__ */ new Set();
|
||||
this._autoClosingTags = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "MENUITEM", "META", "PARAM", "SOURCE", "TRACK", "WBR"]);
|
||||
this._booleanAttributes = /* @__PURE__ */ new Set(["checked", "selected", "disabled", "readonly", "multiple"]);
|
||||
this._eventTypes = /* @__PURE__ */ new Map([
|
||||
@@ -6633,10 +6632,6 @@ var InjectedScript = class {
|
||||
["deviceorientationabsolute", "deviceorientation"],
|
||||
["devicemotion", "devicemotion"]
|
||||
]);
|
||||
this._hoverHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousemove"]);
|
||||
this._tapHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["pointerdown", "pointerup", "touchstart", "touchend", "touchcancel"]);
|
||||
this._mouseHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousedown", "mouseup", "pointerdown", "pointerup", "click", "auxclick", "dblclick", "contextmenu"]);
|
||||
this._allHitTargetInterceptorEvents = /* @__PURE__ */ new Set([...this._hoverHitTargetInterceptorEvents, ...this._tapHitTargetInterceptorEvents, ...this._mouseHitTargetInterceptorEvents]);
|
||||
this._engines = /* @__PURE__ */ new Map();
|
||||
this._engines.set("xpath", XPathEngine);
|
||||
this._engines.set("xpath:light", XPathEngine);
|
||||
@@ -6676,22 +6671,25 @@ var InjectedScript = class {
|
||||
this._shouldPrependErrorPrefix = !!options.shouldPrependErrorPrefix;
|
||||
this._isUtilityWorld = !!options.isUtilityWorld;
|
||||
setGlobalOptions({ browserNameForWorkarounds: options.browserName });
|
||||
if (this._isUtilityWorld) {
|
||||
// MODIFIED by invisible_playwright: these two installations run ONLY
|
||||
// nel mondo di utilita. Nel mondo MAIN usavano l addEventListener della
|
||||
// PAGINA, e un sito che lo avvolge contava TREDICI listener a ogni
|
||||
// bounding_box(): un __ctx_ping__ piu i dodici intercettori di hit-target.
|
||||
// Misurato il 2026-08-27 con lo stack dei chiamanti, non dedotto.
|
||||
//
|
||||
// Nel mondo MAIN erano gia INERTI: _hitTargetInterceptor lo imposta solo il
|
||||
// percorso delle azioni, che gira nel mondo di utilita, quindi il listener
|
||||
// chiamava sempre un undefined. Zero costo funzionale, tredici tracce in meno.
|
||||
//
|
||||
// La riga sopra sa gia in quale mondo siamo, quindi la guardia sta dove il
|
||||
// fatto e noto e non in un terzo posto che dovrebbe restare daccordo.
|
||||
this._setupGlobalListenersRemovalDetection();
|
||||
this._setupHitTargetInterceptors();
|
||||
}
|
||||
// MODIFIED by invisible_playwright: this bundle NEVER touches the page's
|
||||
// window. Not here, and not later.
|
||||
//
|
||||
// Two installations used to live on this line, and an earlier fix only
|
||||
// moved them into the utility world - which was not enough, because
|
||||
// `this.window` there IS the page's window seen through an Xray, so a CALL
|
||||
// on it lands on the page either way. Constructing the script registered
|
||||
// THIRTEEN capture listeners for the life of the document, and replacing
|
||||
// documentElement dispatched a CustomEvent on the page's window that a
|
||||
// site could listen for in three lines.
|
||||
//
|
||||
// They are gone, not renamed and not narrowed: the hit-target check is a
|
||||
// pure DOM read now (`checkHitTarget`), which the caller runs before the
|
||||
// action and again after. Nothing listens, so nothing has to survive a
|
||||
// documentElement replacement, so the detector that announced itself has
|
||||
// no reason to exist.
|
||||
//
|
||||
// `tests/gates/injected_page_surface.js` measures this: zero touches, in
|
||||
// every phase.
|
||||
if (this.isUnderTest)
|
||||
this.window.__injectedScript = this;
|
||||
}
|
||||
@@ -7416,44 +7414,25 @@ var InjectedScript = class {
|
||||
// 2k. (injected) Event interceptor is removed.
|
||||
// 2l. All navigations triggered between 2g-2k are awaited to be either committed or canceled.
|
||||
// 2m. If failed, wait for increasing amount of time before the next retry.
|
||||
setupHitTargetInterceptor(node, action, hitPoint, blockAllEvents) {
|
||||
// MODIFIED by invisible_playwright: a pure read. It used to install capture
|
||||
// listeners on the page's window and validate each event AS IT ARRIVED,
|
||||
// blocking the ones that landed elsewhere. Both halves are gone.
|
||||
//
|
||||
// The listeners were the last thing this bundle put on the page, and the
|
||||
// blocking was itself the tell: a REAL mousedown that vanishes under
|
||||
// preventDefault is something no input stack produces, so the defence
|
||||
// announced us exactly when it worked.
|
||||
//
|
||||
// What survives is the hit test, which was never the problem: it only READS
|
||||
// the DOM, and it reads it through the Xray like everything else here. The
|
||||
// caller runs it before the action and again after, so a target that moved
|
||||
// becomes a retry instead of a blocked event.
|
||||
checkHitTarget(node, hitPoint) {
|
||||
const element = this.retarget(node, "button-link");
|
||||
if (!element || !element.isConnected)
|
||||
return "error:notconnected";
|
||||
if (hitPoint) {
|
||||
const preliminaryResult = this.expectHitTarget(hitPoint, element);
|
||||
if (preliminaryResult !== "done")
|
||||
return preliminaryResult.hitTargetDescription;
|
||||
}
|
||||
if (action === "drag")
|
||||
return { stop: () => "done" };
|
||||
const events = {
|
||||
"hover": this._hoverHitTargetInterceptorEvents,
|
||||
"tap": this._tapHitTargetInterceptorEvents,
|
||||
"mouse": this._mouseHitTargetInterceptorEvents
|
||||
}[action];
|
||||
let result;
|
||||
const listener = (event) => {
|
||||
if (!events.has(event.type))
|
||||
return;
|
||||
if (!event.isTrusted && !event.__pwTrustedSynthetic)
|
||||
return;
|
||||
const point = !!this.window.TouchEvent && event instanceof this.window.TouchEvent ? event.touches[0] : event;
|
||||
if (result === void 0 && point)
|
||||
result = this.expectHitTarget({ x: point.clientX, y: point.clientY }, element);
|
||||
if (blockAllEvents || result !== "done" && result !== void 0) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.stopImmediatePropagation();
|
||||
}
|
||||
};
|
||||
const stop = () => {
|
||||
if (this._hitTargetInterceptor === listener)
|
||||
this._hitTargetInterceptor = void 0;
|
||||
return result || "done";
|
||||
};
|
||||
this._hitTargetInterceptor = listener;
|
||||
return { stop };
|
||||
const result = this.expectHitTarget(hitPoint, element);
|
||||
return result === "done" ? "done" : result.hitTargetDescription;
|
||||
}
|
||||
dispatchEvent(node, type, eventInitObj) {
|
||||
var _a, _b, _c, _d, _e;
|
||||
@@ -7724,39 +7703,6 @@ var InjectedScript = class {
|
||||
// Only the snapshot Streamer listened to them: the trace
|
||||
// viewer. Outside that case they went to nobody at all.
|
||||
}
|
||||
_setupGlobalListenersRemovalDetection() {
|
||||
// MODIFIED by invisible_playwright: neutral name. This CustomEvent
|
||||
// viaggia sul window della PAGINA, e un sito che sostituisce
|
||||
// documentElement e ascolta quel nome otteneva un riscontro.
|
||||
const customEventName = "__ctx_ping__";
|
||||
let seenEvent = false;
|
||||
const handleCustomEvent = () => seenEvent = true;
|
||||
this.window.addEventListener(customEventName, handleCustomEvent);
|
||||
new MutationObserver((entries) => {
|
||||
const newDocumentElement = entries.some((entry) => Array.from(entry.addedNodes).includes(this.document.documentElement));
|
||||
if (!newDocumentElement)
|
||||
return;
|
||||
seenEvent = false;
|
||||
this.window.dispatchEvent(new CustomEvent(customEventName));
|
||||
if (seenEvent)
|
||||
return;
|
||||
this.window.addEventListener(customEventName, handleCustomEvent);
|
||||
for (const callback of this.onGlobalListenersRemoved)
|
||||
callback();
|
||||
}).observe(this.document, { childList: true });
|
||||
}
|
||||
_setupHitTargetInterceptors() {
|
||||
const listener = (event) => {
|
||||
var _a;
|
||||
return (_a = this._hitTargetInterceptor) == null ? void 0 : _a.call(this, event);
|
||||
};
|
||||
const addHitTargetInterceptorListeners = () => {
|
||||
for (const event of this._allHitTargetInterceptorEvents)
|
||||
this.window.addEventListener(event, listener, { capture: true, passive: false });
|
||||
};
|
||||
addHitTargetInterceptorListeners();
|
||||
this.onGlobalListenersRemoved.add(addHitTargetInterceptorListeners);
|
||||
}
|
||||
async expect(element, options, elements) {
|
||||
const core = await this._expectCore(element, options, elements);
|
||||
const ariaSnapshot = core.matches !== options.isNot ? void 0 : this._ariaSnapshotForExpect(element, options);
|
||||
|
||||
@@ -52,7 +52,24 @@ class InjectedScript:
|
||||
self.session = session
|
||||
#: (frameId, worldName) -> executionContextId
|
||||
self.contexts: dict = {}
|
||||
#: frameId -> objectId of the InjectedScript
|
||||
#: frameId -> (executionContextId it was built in, objectId)
|
||||
#:
|
||||
#: ⛔ THE CONTEXT IS PART OF THE KEY, AND IT IS NOT BOOKKEEPING: it is
|
||||
#: what makes a stale handle impossible to use instead of merely
|
||||
#: unlikely. An objectId means nothing on its own - the engine looks it
|
||||
#: up in the worlds the frame has NOW - so a handle is only the handle
|
||||
#: for as long as the world it was minted in is still the frame's
|
||||
#: utility world. Storing the pair lets `handle()` ask that question
|
||||
#: directly; storing the objectId alone left it to be inferred from the
|
||||
#: destruction events arriving complete and in order, and they do not.
|
||||
#:
|
||||
#: Measured 2026-09-16 on a back forward cache restore: the engine
|
||||
#: destroyed contexts id-16 and id-17, which this client had never been
|
||||
#: told about - it believed the frame's worlds were id-14 and id-15 -
|
||||
#: so no entry matched, nothing was dropped, and the next locator sent
|
||||
#: an objectId minted in id-15 to a frame whose worlds were now id-20
|
||||
#: and id-21. `Cannot find object with id`, while `evaluate()` kept
|
||||
#: working because it resolves the context afresh every time.
|
||||
self._handle: dict = {}
|
||||
#: The caller's own init scripts, in the order they were added. Kept
|
||||
#: here because this object is the one that owns the engine's init
|
||||
@@ -80,13 +97,19 @@ class InjectedScript:
|
||||
dead = p["executionContextId"]
|
||||
for k in [k for k, v in self.contexts.items() if v == dead]:
|
||||
self.contexts.pop(k, None)
|
||||
# ⛔ And the handle is discarded: an objectId of a destroyed
|
||||
# context does not fail right away, it gives WRONG results.
|
||||
# The document changed underneath, so the injected script
|
||||
# must be rebuilt.
|
||||
for f in [f for f, _ in list(self._handle.items())
|
||||
if (f, UTILITY_WORLD) not in self.contexts]:
|
||||
self._handle.pop(f, None)
|
||||
# ⛔ NOTHING IS DISCARDED HERE ANY MORE, and that is the fix rather
|
||||
# than an omission. This used to drop a frame's handle when the
|
||||
# frame's utility world had just left `contexts`, which is right
|
||||
# only while every destruction is announced with an id this client
|
||||
# already knows. On a back forward cache restore it is not: the
|
||||
# engine destroys the worlds of the document it is leaving, and
|
||||
# those can be worlds this client was never told were created, so
|
||||
# no entry matched and the handle survived its world.
|
||||
#
|
||||
# `handle()` now asks the question directly instead, which cannot
|
||||
# be wrong: a handle is usable exactly while the context it was
|
||||
# minted in is still the frame's utility context. Whether an event
|
||||
# arrived stops mattering.
|
||||
|
||||
# ── the world ───────────────────────────────────────────────────────────
|
||||
def install(self) -> None:
|
||||
@@ -188,9 +211,24 @@ class InjectedScript:
|
||||
return r.get("value") if by_value else r.get("objectId")
|
||||
|
||||
def handle(self, frame_id: str) -> str:
|
||||
"""The frame's InjectedScript, built only once."""
|
||||
if frame_id in self._handle:
|
||||
return self._handle[frame_id]
|
||||
"""The frame's InjectedScript, built once per world it lives in.
|
||||
|
||||
⛔ "Built only once" was the old sentence and it was the bug. Once per
|
||||
FRAME is wrong: the script is an object inside one execution context,
|
||||
and the frame outlives its contexts - every navigation replaces them,
|
||||
and so does a restore from the back forward cache. What this returns
|
||||
has to be the script of the world the frame has NOW.
|
||||
|
||||
Asking `contexts` is the whole of the check, and it is decidable at any
|
||||
moment from state this client already keeps. The alternative, which is
|
||||
what stood here, was to keep the objectId and trust that some earlier
|
||||
event had removed it when it went stale; a restore is exactly where
|
||||
that trust is misplaced.
|
||||
"""
|
||||
current = self.contexts.get((frame_id, UTILITY_WORLD))
|
||||
cached = self._handle.get(frame_id)
|
||||
if cached is not None and current is not None and cached[0] == current:
|
||||
return cached[1]
|
||||
options = {
|
||||
# ⛔ `isUnderTest` FALSE, always. If true, the InjectedScript
|
||||
# plants `window.builtins` and `window.__injectedScript` on
|
||||
@@ -214,12 +252,18 @@ class InjectedScript:
|
||||
"return new (module.exports.InjectedScript())"
|
||||
"(globalThis, %s); })();"
|
||||
% (source, json.dumps(options)))
|
||||
# ⛔ THE CONTEXT IS READ AGAIN HERE, NOT REUSED FROM ABOVE. `evaluate`
|
||||
# waits for the utility world to exist, so between the check at the top
|
||||
# and this line the frame may have gained one, or gained a different
|
||||
# one. Pairing the objectId with the context it was actually minted in
|
||||
# is the whole point; pairing it with the context we hoped for would
|
||||
# recreate the same class one layer down.
|
||||
oid = self.evaluate(frame_id, expression, by_value=False)
|
||||
if not oid:
|
||||
raise EvaluationError(
|
||||
"the InjectedScript did not return an object: "
|
||||
"is the source the right one?")
|
||||
self._handle[frame_id] = oid
|
||||
self._handle[frame_id] = (self.context_id(frame_id), oid)
|
||||
return oid
|
||||
|
||||
# ── the little needed on top ────────────────────────────────────────────
|
||||
@@ -329,6 +373,40 @@ class InjectedScript:
|
||||
" return el.getBoundingClientRect().top !== before; }",
|
||||
{"objectId": element}))
|
||||
|
||||
def content_origin(self, frame_id: str) -> dict:
|
||||
"""Where this frame's content area starts, in SCREEN css pixels.
|
||||
|
||||
⛔ IT COMES FROM THE ENGINE, and that is the whole point. The hit
|
||||
point a caller has is in the MAIN frame's space, because that is what
|
||||
`Page.getContentQuads` answers and what `dispatchMouseEvent` wants. To
|
||||
check it inside a nested frame it has to be expressed in THAT frame's
|
||||
space, and the difference between the two origins is exactly the shift.
|
||||
Reading it from `mozInnerScreen*` keeps one source: this project already
|
||||
owns that value in C++ (`StealthDeclaredContentOrigin`), so a second
|
||||
arithmetic here would be the duplicate that rule 16 is about.
|
||||
"""
|
||||
return self.evaluate(
|
||||
frame_id,
|
||||
"({x: window.mozInnerScreenX, y: window.mozInnerScreenY})")
|
||||
|
||||
def check_hit_target(self, frame_id: str, element: str, point) -> str:
|
||||
"""Does `point` still belong to `element`? `"done"`, or what is there.
|
||||
|
||||
⛔ A PURE READ, and it replaced an interceptor. The bundle used to
|
||||
install capture listeners on the page's window and validate each event
|
||||
as it ARRIVED, blocking the ones that landed elsewhere. That was the
|
||||
last thing this package put on the page, and the blocking was itself a
|
||||
tell: a real `mousedown` that disappears under `preventDefault` is not
|
||||
something an input stack produces.
|
||||
|
||||
The caller runs this BEFORE the action and again AFTER, which turns a
|
||||
target that moved into a retry instead of into a blocked event.
|
||||
"""
|
||||
return self.call(
|
||||
frame_id,
|
||||
"(injected, el, x, y) => injected.checkHitTarget(el, {x, y})",
|
||||
{"objectId": element}, float(point[0]), float(point[1]))
|
||||
|
||||
def element_states(self, frame_id: str, element: str,
|
||||
states: list) -> dict:
|
||||
"""Asks the injected script whether the element is actionable.
|
||||
|
||||
@@ -30,6 +30,7 @@ and rewritten.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from .keylayout import LAYOUT
|
||||
@@ -121,11 +122,28 @@ class Keyboard:
|
||||
remember that Shift is down between Shift's keydown and `a`'s.
|
||||
"""
|
||||
|
||||
def __init__(self, connection, session: str):
|
||||
def __init__(self, connection, session: str, persona=None):
|
||||
self.c = connection
|
||||
self.session = session
|
||||
self.modifiers: set = set()
|
||||
self.pressed: set = set()
|
||||
#: ⛔ THE RHYTHM HAS AN OWNER NOW, and this is it.
|
||||
#:
|
||||
#: A keypress used to be two protocol messages back to back, so a page
|
||||
#: saw `keydown` and `keyup` about 2.4 ms apart and two characters
|
||||
#: about 5 ms apart, against the 60-250 ms a hand produces. No probe is
|
||||
#: needed to collect that: a site only has to listen, and a password
|
||||
#: field is where the listening is already installed.
|
||||
#:
|
||||
#: The persona is DRAWN FROM THE SESSION SEED and computed by the
|
||||
#: wrapper, not here: this class obeys a plan, it does not invent one.
|
||||
#: `None` means no rhythm, which is what a caller who turned humanising
|
||||
#: off asked for.
|
||||
self.persona = persona
|
||||
#: One stream per keyboard, so two `type()` calls in a session do not
|
||||
#: replay the same intervals. Without it a page could match the
|
||||
#: sequence of gaps between two form fields.
|
||||
self._nonce = 0
|
||||
|
||||
# ── the resolution ──────────────────────────────────────────────────────
|
||||
def describe(self, key: str) -> dict:
|
||||
@@ -187,11 +205,20 @@ class Keyboard:
|
||||
"location": d["location"], "repeat": False},
|
||||
session=self.session, timeout=10)
|
||||
|
||||
def press(self, key: str) -> None:
|
||||
def press(self, key: str, *, dwell_ms: Optional[float] = None) -> None:
|
||||
"""`press("a")`, `press("Enter")`, `press("Control+Shift+KeyA")`.
|
||||
|
||||
The modifiers are held down for the whole final key and released
|
||||
in reverse order, the way a hand would.
|
||||
|
||||
⛔ `dwell_ms` IS HOW LONG THE KEY STAYS DOWN, and the unit is in the
|
||||
name on purpose: see the note on `type`. Zero was the only value this
|
||||
could produce before, which put `keyup` one protocol round trip after
|
||||
`keydown` - about 2.4 ms, where a finger takes 60-120.
|
||||
|
||||
It applies to the FINAL key only. A modifier is held across the whole
|
||||
press by construction, so giving it a dwell of its own would be a
|
||||
second statement about the same duration.
|
||||
"""
|
||||
pieces = key.split("+")
|
||||
final, held = pieces[-1], pieces[:-1]
|
||||
@@ -201,34 +228,85 @@ class Keyboard:
|
||||
# "unknown key: ''".
|
||||
if final == "" and held:
|
||||
final, held = "+", held[:-1]
|
||||
# ⛔ `None` means "ask the hand", not "zero". Playwright's own
|
||||
# `keyboard.press(key, delay=)` IS this number - it documents it as the
|
||||
# wait between keydown and keyup - so a caller who passes it overrides
|
||||
# the persona for that press, and a caller who passes nothing gets the
|
||||
# session's hand rather than a pipe round trip.
|
||||
if dwell_ms is None:
|
||||
dwell_ms = self._dwell_ms()
|
||||
for m in held:
|
||||
self.down(m)
|
||||
try:
|
||||
self.down(final)
|
||||
if dwell_ms > 0.0:
|
||||
time.sleep(dwell_ms / 1000.0)
|
||||
self.up(final)
|
||||
finally:
|
||||
for m in reversed(held):
|
||||
self.up(m)
|
||||
|
||||
def type(self, text: str, *, delay: float = 0.0) -> None:
|
||||
"""One key per character, the way a hand would.
|
||||
def type(self, text: str, *, delay_ms: float = 0.0) -> None:
|
||||
"""One key per character, with the rhythm of a hand.
|
||||
|
||||
⛔ This is NOT `insert_text`: a character the layout does not know
|
||||
(an ideogram, an emoji) has no key, so here it is REJECTED and
|
||||
deferred to `insert_text`. Typing something with no key would mean
|
||||
sending `code: ""`, which is exactly the defect this file exists
|
||||
to not have.
|
||||
|
||||
⛔ THE UNIT IS IN THE NAME, AND IT IS A FIX. The parameter used to be
|
||||
called `delay` and was handed straight to `time.sleep`, which takes
|
||||
SECONDS, while the public API documents it in MILLISECONDS. On the one
|
||||
path that actually forwarded it - the ElementHandle one - `type("abc",
|
||||
delay=100)` therefore slept for five minutes instead of 0.3 seconds.
|
||||
The six paths that dropped the value were accidentally protected from
|
||||
the bug the seventh had.
|
||||
|
||||
⛔ AND THE CALLER'S VALUE IS AN OVERRIDE, NOT THE DEFENCE. Without a
|
||||
persona this class used to emit keys as fast as the pipe allows, so the
|
||||
only thing standing between a caller and an inhuman rhythm was a
|
||||
parameter they had to know to pass - and every install that passed
|
||||
`delay=100` would have shared one flat rhythm, which is a key that
|
||||
links them. The persona is per-session and is what runs when nobody
|
||||
asks for anything.
|
||||
"""
|
||||
import time as _t
|
||||
for ch in text:
|
||||
if ch not in LAYOUT_CLOSURE:
|
||||
raise UnknownKey(
|
||||
"%r has no key on the US layout: use `insert_text`, "
|
||||
"which goes through `Page.insertText` and does not "
|
||||
"fake a keypress." % ch)
|
||||
self.press(ch)
|
||||
if delay:
|
||||
_t.sleep(delay)
|
||||
|
||||
plan = self._plan(text)
|
||||
for i, ch in enumerate(text):
|
||||
dwell_ms, gap_ms = plan[i]
|
||||
self.press(ch, dwell_ms=dwell_ms)
|
||||
wait_ms = delay_ms if delay_ms else gap_ms
|
||||
if wait_ms > 0.0 and i < len(text) - 1:
|
||||
time.sleep(wait_ms / 1000.0)
|
||||
|
||||
def _dwell_ms(self) -> float:
|
||||
"""How long ONE key stays down, for a press that is not part of typed
|
||||
text. Zero without a persona, which is what turning humanising off
|
||||
means."""
|
||||
if self.persona is None:
|
||||
return 0.0
|
||||
return self._plan("x")[0][0]
|
||||
|
||||
def _plan(self, text: str):
|
||||
"""One `(dwell_ms, gap_ms)` per character, from the session's persona.
|
||||
|
||||
⛔ Falls back to no rhythm rather than to a made-up one. A default
|
||||
constant here would be the shared invariant the persona exists to
|
||||
remove, and it would be invisible: every install would type alike and
|
||||
nothing would report it.
|
||||
"""
|
||||
if self.persona is None:
|
||||
return [(0.0, 0.0)] * len(text)
|
||||
from .._behaviour import plan_typing
|
||||
self._nonce += 1
|
||||
return plan_typing(text, self.persona, nonce=self._nonce)
|
||||
|
||||
def insert_text(self, text: str) -> None:
|
||||
"""The text goes in without key events. This is what is needed for
|
||||
|
||||