purecdp
Pure-Python (stdlib-only) library for the Chrome DevTools Protocol, targeting Python 3.14+.
Three things, layered:
purecdp.protocol— low-level typed bindings, generated from the official devtools-protocol JSON specs. Names are bare —TargetInfo.type,Frame.id,dispatch_mouse_event(type=...)— not thetype_/id_trailing-underscore convention some CDP generators use (they aren't Python keywords, so nothing needs mangling).purecdpcore — sans-I/O protocol engine + asyncio transports (websocket / pipe) + browser launcher.purecdp.testing— opinionated helpers for driving a browser in tests, incl. a pytest plugin.
See Examples.md for task-grouped recipes (basics, testing, stealth, LLM agents, frames).
Quickstart
import asyncio
import purecdp
from purecdp.protocol import page, runtime
async def main():
async with await purecdp.launch() as browser: # finds Chromium/Chrome/Brave
session = await browser.new_session() # create target + attach
await session.execute(page.enable())
waiter = asyncio.create_task(session.wait_for(page.LoadEventFired))
await asyncio.sleep(0) # subscribe before triggering
await session.execute(page.navigate(url="https://example.com"))
await waiter
result, _ = await session.execute(
runtime.evaluate(expression="document.title", return_by_value=True))
print(result.value)
asyncio.run(main())
purecdp.launch(pipe=True) uses --remote-debugging-pipe instead of a websocket.
browser.new_page() is the one-call convenience — a new tab as a ready
testing.Page. purecdp.connect("http://127.0.0.1:9222") (or host=/port=,
or a ws:// endpoint) attaches to a browser someone else started — notably a
browser a human just logged into (password, MFA), so an agent can inherit the
authenticated session while the credentials never touch the automation; a new
tab shares the profile's cookies, so it's signed in from birth — and
browser.attach(url_contains="kais") grabs an already-open tab as a ready
Page (no-arg attach() = the realized page tab; no match, or several,
raises TargetNotFound naming the tabs that do exist).
browser.new_context() gives an isolated cookies/storage context (cheap per-test
isolation); connection.set_auto_attach() auto-attaches popups/workers/OOPIFs,
resuming paused targets automatically.
Writing tests with purecdp
The stdlib way (purecdp.testing.CDPTestCase — fresh browser, isolated
context, and a Page per test):
from purecdp.testing import CDPTestCase, JSError
class MyAppTests(CDPTestCase):
async def test_stubbed_api(self):
async def api(request):
await request.fulfill(body='{"items": []}',
content_type="application/json")
await self.page.route("*/api/*", api)
await self.page.goto("https://myapp.example/", wait="idle")
await self.page.wait_for("#empty-state")
assert not self.page.js_errors
Page gives you goto (load/idle waits), evaluate (promises awaited,
JSError raised; values pass as arguments —
evaluate("(a, b) => a + b", x, y) — never interpolated into JS source),
wait_for(selector, **conditions) (present / visible=False gone-or-hidden /
count=0 absent — the should() vocabulary), wait_for_function, click,
query/query_all (held elements, text-filtered, stale-copy-proof),
screenshot, always-on page.console / page.js_errors capture,
page.route() request stubbing/rewriting/aborting (the intercepted request
exposes .post_data / .json / .header()), page.mock_api() for
path-keyed stubs and page.relay(prefix, origin) to forward a path prefix to
a real backend — stub or forward, composable either way. An action on a
handle the app has since replaced raises ActionabilityError (detached)
rather than typing into the void. For traffic-level
assertions there's page.record() (full request/response exchanges — the
wire headers, Cookie / Origin / Set-Cookie included, plus bodies, and
parse_sse() for streamed ones) and page.expect_download() (capture a
download's bytes without touching disk); arm recorder.expect() before a
click and await .value for the response it triggers (json=True skips
interleaved non-JSON bodies, where= takes any predicate), recorder.wait_for(count=2, where=...) waits for several, and recorder.save_har() writes the whole
capture as a HAR any devtools opens. Sensitive flows keep their privacy:
record(bodies=False) captures metadata only, and record(redact=...) makes
matching exchanges fully private (no bodies, credential headers masked) — the
secret never enters the process. And when a test fails, its pages
are dumped as diagnostic artifacts — screenshot, HTML, console, recorded
traffic, traceback — under purecdp-artifacts/<test id>/ before the browser
closes; green tests write nothing (standalone drive scripts get the same
from Checks: a failed check() dumps artifacts right then). Long-running
watchers get an honest
give-up signal: page.alive (False once the tab or browser is gone; no
round-trip) and the CDPClosedError base (CDPSessionClosed +
CDPConnectionClosed), so while page.alive: with
except CDPClosedError: break can never spin on a dead tab.
For SPA-proof tests there are lazy locators: page.live(selector) and
get_by_test_id / get_by_text / get_by_role / get_by_label hold the
query, not a node — every action re-resolves against the current DOM (a
React remount can't leave you a stale handle), auto-waits for actionability,
and one .should(...) gives polling assertions:
await page.get_by_test_id("chat-input").fill("hello")
await page.get_by_role("button", name="Send").click()
await page.live(".msg", containing="hello").should(visible=True, count=1)
await page.live(".spinner").should(count=0) # waits until it's gone
Prefer pytest? The optional plugin (auto-registered when installed, or
-p purecdp.testing.pytest_plugin) provides a session-scoped cdp_browser
and per-test cdp_page, and runs async def tests itself — no
pytest-asyncio required:
async def test_title(cdp_page):
await cdp_page.goto("data:text/html,<title>hi</title>")
assert await cdp_page.title() == "hi"
Low-observability / stealth
For automation that shouldn't advertise itself, purecdp layers three opt-in pieces (reduces common detection signals — not a promise of undetectability; CreepJS-class and TLS/HTTP2 fingerprints still identify automation):
import purecdp
from purecdp.testing import Page, apply_stealth
async with await purecdp.launch(stealth=True) as browser: # AutomationControlled off, headless=new
session = await browser.new_session()
page = await Page.create(session, capture=False, track_network=False) # no Runtime.enable leak
await apply_stealth(page) # fingerprint init-scripts, before goto
await page.goto("https://example.com")
apply_stealth(page, evasions=[...]) selects a subset; keyword overrides
(webgl_vendor, webgl_renderer, languages, vendor,
hardware_concurrency) tune the spoofed values.
For behavioral realism (the more durable signal — how input moves, all over trusted Input events):
el = await page.query("#submit")
await el.human_click() # curved, eased path to a near-center point
await page.human_type("hello@example.com") # per-key events, human cadence
await page.human_scroll(1200) # eased wheel steps, not one jump
Since purecdp drives a real browser, its TLS/HTTP2 (JA3/JA4) fingerprint is already authentically Chrome's — no spoofing needed, unlike browserless HTTP scrapers.
Field notes
Lessons from real scraping/automation runs, cheapest first:
- Check for SSR state before driving a browser. Many SPAs ship their whole
data model inside the HTML —
<script id="serverApp-state" type="application/json">(Angular Universal),__NEXT_DATA__(Next.js),__NUXT__(Nuxt). One plain HTTP GET plusjson.loadsbeats a browser session in speed and reliability; purecdp is for pages that genuinely render client-side. - Heavy SPAs never fire
loadquickly.gotowaits for'load'with a 10 s default; for Google-Maps-class pages passawait page.goto(url, wait='domcontentloaded')(or raisetimeout=) and poll for the element you need. - The reliable
evaluateidiom is strings both ways:JSON.stringify(...)on the JS side,json.loads(...)on the Python side. It sidesteps any question of how richer values marshal. - Headed mode can leave the profile locked. After a headed run a browser
process could keep holding
user_data_dir— a wrapper script re-execs, so signalling the spawned child may miss the real browser.aclose()therefore closes gracefully first:Browser.closeover CDP reaches the real browser whatever its PID, and it exits cleanly, releasing the lock (signals are only the fallback). If a profile is still held,launch()diagnoses it instead of failing obscurely: aSingletonLockpointing at a live process raisesBrowserLaunchError: profile … in use by PID N, a staleDevToolsActivePortis cleared (it used to surface as a bafflingConnectionRefusedErrorto a dead port), and any launch failure quotes the browser's own stderr. - Some Chromium forks never realize CDP-created tabs. Vivaldi (confirmed)
accepts
Target.createTarget, returns an id, even lets you attach — but the tab never comes to exist: its URL stays empty, there is no renderer, and any navigation on it hangs forever.new_session()/new_page()detect this and raiseTargetNotRealizednaming the browser instead of hanging. The fix is to drive an existing tab: no-argbrowser.attach()picks the realized page tab, skipping empty-URL zombies andchrome://-style UI targets. Likely applies to other forks with their own tab UI (Opera, Arc) — "attach works, create doesn't." - Search-engine bot walls are IP-reputation, not fingerprints. From a
flagged IP,
stealth=Truedoes not move the needle on google.com/search — yet Google Maps place pages load fine in the same session, and independent engines captcha on volume. Pick targets, not evasions.
Driving with an LLM (agent surface)
page.snapshot() returns a compact, ref-tagged view of the page from the
accessibility tree — small and stable enough to hand an LLM, instead of raw
HTML or screenshots. Each control gets a session ref (e1, e2, …); password
fields are masked.
snap = await page.snapshot()
print(snap)
# - RootWebArea "Login"
# - textbox "Email" [e1]
# - textbox "Password" = "••••••" [e2]
# - button "Sign in" [e3]
await page.act("e1", "fill", text="me@example.com") # fill/type/select/click/…
await page.act("e3", "click")
el = await page.element_for_ref("e1") # escape hatch: full Element API
An optional MCP server exposes this to any Model Context Protocol host — no extra dependency, stdlib JSON-RPC over stdio:
python -m purecdp.mcp # navigate/snapshot/act + network/wait/seed tools
python -m purecdp.mcp --stealth # low-observability launch
python -m purecdp.mcp --allow-eval # also expose the JS evaluate tool
python -m purecdp.mcp --allow-mock # also expose the response-stubbing tool
Beyond driving the DOM, the server exposes the recorder so an agent can assert
on the wire: after act, the returned cursor feeds requests(since=cursor) to
see what the click fired, then request(id, select="a.b") reads just that part
of the response body (semantic projection, so a huge body doesn't flood the
agent's context). act targets an element by snapshot ref or by description
(by=text/role/testid/label); snapshot returns the ref-tagged outline
or (format="json") a flat list of {ref, role, name} rows, and
(scope="dialog") narrows to the open modal's controls; screenshot
returns a PNG image block for visual state; plus wait (until visible/hidden/
count/text), seed_storage / set_cookie (plant an auth session before
navigating), record (narrow capture), and mock (stub an endpoint, opt-in).
Three things worth knowing. snap.find("button", "sign in") returns the first
matching ref (role exact, name a case-insensitive substring, exact=True or a
compiled regex for more), find_all every match — the loop every drive used to
write. The outline comes from purecdp's in-page walker by default: one
evaluate, about 3× faster than pulling the browser's whole accessibility tree
over the wire (31 vs 85 ms on a 300-row table), fewer wrapper rows, and it
matched Chrome's native control set exactly on seven real pages in the test
suite's dogfood; page.snapshot(engine="native") (or
page.snapshot_engine = "native", --snapshot-engine native for the MCP
server) asks Chromium's Accessibility domain instead — Firefox has no tree
command and always walks. And every page starts with a 1280×720 viewport
(Page.create(viewport=None) to keep the browser's own; launch(window_size=)
sizes the window itself).
Firefox (experimental)
Firefox speaks WebDriver BiDi, not CDP. launch(browser="firefox") (or any
browser_path whose name says firefox) starts it, connects over BiDi and hands
back the same Page API, so a drive's scripting, navigation, console capture,
queries, screenshots and PDF work unchanged:
async with await purecdp.launch(browser="firefox") as browser:
page = await browser.new_page()
await page.goto("https://example.com")
print(await page.evaluate("(sel) => document.querySelector(sel).textContent", "h1"))
Trusted input (type, press, mouse_click, the human cursor), cookies,
extra headers, user-agent / geolocation / timezone overrides, dialogs, frames
(page.frame() reaches same-origin iframes too — on BiDi every iframe is a
browsing context), apply_stealth / launch(stealth=True) (the engine-neutral
subset, browser-wide at launch: navigator.webdriver reads false) and CDPTestCase with BROWSER_KIND = "firefox" (or
PURECDP_E2E_BROWSER=firefox), request interception (route, mock_api,
relay), the network recorder with bodies, expect_download, and the agent
surface — snapshot(), act(), cross-frame snapshots and the MCP server
(python -m purecdp.mcp --browser firefox) — all work. BiDi has no
accessibility-tree command, so on Firefox the outline comes from an in-page
walker that is validated against Chrome's real tree in the test suite; it is
an approximation by design (an outline for a model, not a screen reader). The
one thing that raises NotSupported is media emulation, which has no BiDi
equivalent at all. Two documented differences:
type(insert=True) is typed as key events on Firefox (there is no
insertText, so key listeners fire), and page.session is None (page.bidi
is the raw escape hatch, await page.bidi.call("module.command", {...})). No
pipe transport. Chromium stays on CDP: Chrome's own BiDi endpoint is a mapper
over CDP, so nothing is gained by switching it.
Drive your own Firefox
Firefox only opens its remote agent when it is started with
--remote-debugging-port (0 = pick a free port; there is no way to turn it on
afterwards), so give your daily Firefox that flag in its launcher. From then on:
import purecdp
profile = purecdp.find_firefox_profile() # from profiles.ini
browser = await purecdp.connect(user_data_dir=profile) # reads WebDriverBiDiServer.json
page = await browser.attach(url_contains="app.example") # a tab you already have open
token = await page.evaluate("localStorage.getItem('token')")
await browser.aclose() # ends purecdp's session; Firefox stays up
connect() also takes the ws://host:port/session endpoint directly, or
browser="firefox" with host/port. Firefox allows a single BiDi session at
a time: a second client is refused with a message saying who to close, and
purecdp releases its own session on aclose(). launch(user_data_dir=profile)
is the other route (Firefox must be closed first): purecdp no longer writes its
quiet-startup prefs into a profile it did not create.
Layout
spec/ vendored protocol JSON + PIN (source commit)
src/purecdp/ the library (src layout)
src/purecdp/_generator/ code generator (dev tool, reads spec/, writes src/purecdp/protocol/)
src/purecdp/protocol/ GENERATED bindings — do not edit by hand
tests/ tests and test utilities
Regenerating the bindings
python -m purecdp._generator # uses spec/ and src/purecdp/protocol/ defaults
Update spec/*.json + spec/PIN from a devtools-protocol checkout first when moving the pin.
Running tests
Stdlib only — no test dependencies:
python -m unittest # discovery from repo root
python tests/test_protocol.py # single file works too
python -m pytest also works (nicer output, subtest counts) but is never required.
Metadata
Release files for purecdp 0.10.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| purecdp-0.10.1.tar.gz | 504.3 kB | With provenance | Details for purecdp-0.10.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| purecdp-0.10.1-py3-none-any.whl | Python 3 | none | any | Details for purecdp-0.10.1-py3-none-any.whl |
Total release size: 963.0 kB
Release files / purecdp-0.10.1.tar.gz
| Download URL | purecdp-0.10.1.tar.gz |
|---|---|
| Size | 504.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5f047f78f347ce2e9b0da51d96c04e4d98ef37dfaf398a052ade36911b2523f8
|
|
BLAKE2b-256 checksum How to use checksums |
5f1eb64780f64a49487eba5980577734f32ef58201034bdef958685cb2180bf6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.
Transparency logRelease files / purecdp-0.10.1-py3-none-any.whl
| Download URL | purecdp-0.10.1-py3-none-any.whl |
|---|---|
| Size | 458.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7d2e7286a3a22955224907d01c2f78243502fdb5a8db67fef0aab19e222ec6c8
|
|
BLAKE2b-256 checksum How to use checksums |
09e54355a24a8f3e0e66bc6a58db717f5b0781a4f2f6e71cfab3a8e42461d78e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.
Transparency logSecurity for purecdp 0.10.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for purecdp-0.10.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.