Skip to content

CDP Client API Reference

Auto-generated API documentation for the CDP Client module.

cdp

Zero-dependency Chrome DevTools Protocol (CDP) client.

Part of zerodep: https://github.com/Oaklight/zerodep Copyright (c) 2026 Peng Ding. MIT License.

Provides sync and async CDP clients for communicating with CDP-compatible browsers (Chrome, Chromium, Lightpanda, etc.) over WebSocket. Supports tab management, page navigation, JavaScript evaluation, and high-level rendered content extraction.

Usage::

# High-level: extract rendered text from an SPA
from cdp import CDPClient

with CDPClient("ws://localhost:9222") as client:
    text = client.get_rendered_text("https://react.dev", timeout=15)
    print(text)

# Low-level: manage targets and evaluate JS
from cdp import CDPClient

with CDPClient("ws://localhost:9222") as client:
    target_id = client.create_target("https://example.com")
    client.wait_for_load(target_id, timeout=10)
    html = client.evaluate(target_id, "document.documentElement.outerHTML")
    client.close_target(target_id)

# Async
from cdp import AsyncCDPClient

async with AsyncCDPClient("ws://localhost:9222") as client:
    text = await client.get_rendered_text("https://example.com")

Requires Python 3.10+.

CDPError

Bases: Exception

Base exception for all CDP operations.

Source code in cdp/cdp.py
class CDPError(Exception):
    """Base exception for all CDP operations."""

CDPConnectionError

Bases: CDPError

Raised on WebSocket connection failures to the CDP endpoint.

Source code in cdp/cdp.py
class CDPConnectionError(CDPError):
    """Raised on WebSocket connection failures to the CDP endpoint."""

    def __init__(self, message: str, *, url: str = "") -> None:
        self.url = url
        super().__init__(message)

CDPTimeoutError

Bases: CDPError

Raised when a CDP operation times out.

Source code in cdp/cdp.py
class CDPTimeoutError(CDPError):
    """Raised when a CDP operation times out."""

    def __init__(self, message: str, *, timeout: float = 0.0) -> None:
        self.timeout = timeout
        super().__init__(message)

CDPProtocolError

Bases: CDPError

Raised on CDP error responses.

Source code in cdp/cdp.py
class CDPProtocolError(CDPError):
    """Raised on CDP error responses."""

    def __init__(
        self,
        code: int,
        message: str,
        *,
        data: str | None = None,
    ) -> None:
        self.code = code
        self.error_message = message
        self.data = data
        super().__init__(f"CDP error {code}: {message}")

CDPClient

Synchronous Chrome DevTools Protocol client.

Parameters:

Name Type Description Default
url str

CDP WebSocket endpoint URL (e.g. ws://localhost:9222). If the URL does not contain a path, the client will auto-discover the browser's debugger WebSocket URL via the /json/version endpoint.

required
timeout float

Default timeout for CDP commands in seconds.

DEFAULT_TIMEOUT

Example::

with CDPClient("ws://localhost:9222") as client:
    text = client.get_rendered_text("https://example.com")
    print(text)
Source code in cdp/cdp.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
class CDPClient:
    """Synchronous Chrome DevTools Protocol client.

    Args:
        url: CDP WebSocket endpoint URL (e.g. ``ws://localhost:9222``).
            If the URL does not contain a path, the client will auto-discover
            the browser's debugger WebSocket URL via the ``/json/version``
            endpoint.
        timeout: Default timeout for CDP commands in seconds.

    Example::

        with CDPClient("ws://localhost:9222") as client:
            text = client.get_rendered_text("https://example.com")
            print(text)
    """

    def __init__(
        self,
        url: str,
        *,
        timeout: float = DEFAULT_TIMEOUT,
    ) -> None:
        self._url = url
        self._timeout = timeout
        self._ws: _WebSocketClient | None = None
        self._cmd_id = itertools.count(1)
        self._targets: dict[str, str] = {}  # target_id -> session_id
        self._event_buffer: collections.deque[dict] = collections.deque()

    def connect(self, *, timeout: float | None = None) -> None:
        """Open the WebSocket connection to the CDP endpoint.

        Args:
            timeout: Connection timeout in seconds. Defaults to the
                client's default timeout.

        Raises:
            CDPConnectionError: If the connection fails.
            ImportError: If the websocket module is not available.
        """
        if self._ws is not None:
            return

        if not _HAS_WEBSOCKET:
            raise ImportError(
                "cdp module requires sibling 'websocket' module; "
                "install it with: zerodep add websocket"
            )

        ws_url = self._resolve_ws_url(self._url, timeout=timeout or self._timeout)

        try:
            ws = _WebSocketClient(ws_url)
            ws.connect(timeout=timeout or self._timeout)
            self._ws = ws
        except _WebSocketConnectionError as exc:
            raise CDPConnectionError(
                f"failed to connect to CDP endpoint: {exc}",
                url=ws_url,
            ) from exc
        except _WebSocketTimeoutError as exc:
            raise CDPTimeoutError(
                f"connection to CDP endpoint timed out: {exc}",
                timeout=timeout or self._timeout,
            ) from exc

    def send_command(
        self,
        method: str,
        params: dict | None = None,
        *,
        session_id: str | None = None,
        timeout: float | None = None,
    ) -> dict:
        """Send a CDP command and wait for the response.

        Args:
            method: CDP method name (e.g. ``Page.navigate``).
            params: Optional command parameters.
            session_id: Optional session ID for target-specific commands.
            timeout: Command timeout in seconds.

        Returns:
            The ``result`` dict from the CDP response.

        Raises:
            CDPTimeoutError: If the command times out.
            CDPProtocolError: If the CDP response contains an error.
            CDPError: If not connected.
        """
        self._ensure_connected()
        assert self._ws is not None

        cmd_id = next(self._cmd_id)
        msg: dict = {"id": cmd_id, "method": method}
        if params:
            msg["params"] = params
        if session_id:
            msg["sessionId"] = session_id

        self._ws.send(json.dumps(msg))
        return self._recv_response(cmd_id, timeout=timeout or self._timeout)

    def create_target(self, url: str = "about:blank") -> str:
        """Create a new browser target (tab) and attach to it.

        Args:
            url: Initial URL to load in the new target.

        Returns:
            The target ID.
        """
        result = self.send_command("Target.createTarget", {"url": url})
        target_id = result["targetId"]

        attach_result = self.send_command(
            "Target.attachToTarget",
            {"targetId": target_id, "flatten": True},
        )
        session_id = attach_result["sessionId"]
        self._targets[target_id] = session_id
        logger.debug("created target %s with session %s", target_id, session_id)
        return target_id

    def close_target(self, target_id: str) -> None:
        """Close a browser target (tab).

        Args:
            target_id: The target ID to close.
        """
        if target_id not in self._targets:
            return
        try:
            self.send_command("Target.closeTarget", {"targetId": target_id})
        except CDPError:
            logger.debug("failed to close target %s", target_id, exc_info=True)
        self._targets.pop(target_id, None)

    def navigate(
        self,
        target_id: str,
        url: str,
        *,
        timeout: float | None = None,
    ) -> None:
        """Navigate a target to a URL and wait for the page to load.

        Args:
            target_id: The target ID.
            url: URL to navigate to.
            timeout: Page load timeout in seconds.
        """
        session_id = self._get_session_id(target_id)
        load_timeout = timeout or DEFAULT_PAGE_LOAD_TIMEOUT

        self.send_command("Page.enable", session_id=session_id)
        self.send_command("Page.navigate", {"url": url}, session_id=session_id)
        self._wait_for_event(
            "Page.loadEventFired",
            session_id=session_id,
            timeout=load_timeout,
        )

    def wait_for_load(
        self,
        target_id: str,
        *,
        timeout: float | None = None,
    ) -> None:
        """Wait for a target's page to finish loading.

        Args:
            target_id: The target ID.
            timeout: Page load timeout in seconds.
        """
        session_id = self._get_session_id(target_id)
        self.send_command("Page.enable", session_id=session_id)
        self._wait_for_event(
            "Page.loadEventFired",
            session_id=session_id,
            timeout=timeout or DEFAULT_PAGE_LOAD_TIMEOUT,
        )

    def evaluate(self, target_id: str, expression: str) -> object:
        """Evaluate a JavaScript expression in a target.

        Args:
            target_id: The target ID.
            expression: JavaScript expression to evaluate.

        Returns:
            The result value.

        Raises:
            CDPProtocolError: If the evaluation throws an exception.
        """
        session_id = self._get_session_id(target_id)
        result = self.send_command(
            "Runtime.evaluate",
            {"expression": expression, "returnByValue": True},
            session_id=session_id,
        )

        if "exceptionDetails" in result:
            exc_details = result["exceptionDetails"]
            text = exc_details.get("text", "evaluation failed")
            raise CDPProtocolError(-1, text)

        return result.get("result", {}).get("value")

    def get_rendered_text(
        self,
        url: str,
        *,
        timeout: float | None = None,
    ) -> str:
        """Navigate to a URL and extract the rendered text content.

        Creates a temporary target, navigates to the URL, waits for load,
        extracts ``document.body.innerText``, and closes the target.

        Args:
            url: URL to render.
            timeout: Page load timeout in seconds.

        Returns:
            The rendered text content of the page.
        """
        target_id = self.create_target()
        try:
            self.navigate(target_id, url, timeout=timeout)
            result = self.evaluate(target_id, "document.body.innerText")
            return result if isinstance(result, str) else str(result or "")
        finally:
            self.close_target(target_id)

    def get_rendered_html(
        self,
        url: str,
        *,
        timeout: float | None = None,
    ) -> str:
        """Navigate to a URL and extract the rendered HTML.

        Creates a temporary target, navigates to the URL, waits for load,
        extracts ``document.documentElement.outerHTML``, and closes the target.

        Args:
            url: URL to render.
            timeout: Page load timeout in seconds.

        Returns:
            The rendered outer HTML of the page.
        """
        target_id = self.create_target()
        try:
            self.navigate(target_id, url, timeout=timeout)
            result = self.evaluate(target_id, "document.documentElement.outerHTML")
            return result if isinstance(result, str) else str(result or "")
        finally:
            self.close_target(target_id)

    def set_user_agent(self, target_id: str, user_agent: str) -> None:
        """Override the User-Agent for a target.

        Args:
            target_id: The target ID.
            user_agent: The User-Agent string to set.
        """
        session_id = self._get_session_id(target_id)
        self.send_command(
            "Network.setUserAgentOverride",
            {"userAgent": user_agent},
            session_id=session_id,
        )

    def close(self) -> None:
        """Close all targets and the WebSocket connection."""
        if self._ws is None:
            return

        # Close all targets (best-effort)
        for target_id in list(self._targets):
            try:
                self.send_command("Target.closeTarget", {"targetId": target_id})
            except (CDPError, _WebSocketError):
                pass
        self._targets.clear()
        self._event_buffer.clear()

        try:
            self._ws.close()
        except _WebSocketError:
            pass
        self._ws = None

    def __enter__(self) -> CDPClient:
        self.connect()
        return self

    def __exit__(self, *args: object) -> None:
        self.close()

    # ── Sync internal helpers ──

    def _ensure_connected(self) -> None:
        if self._ws is None:
            raise CDPError("not connected")

    def _get_session_id(self, target_id: str) -> str:
        session_id = self._targets.get(target_id)
        if session_id is None:
            raise CDPError(f"unknown target: {target_id}")
        return session_id

    def _recv_response(self, cmd_id: int, *, timeout: float) -> dict:
        """Receive messages until the response matching *cmd_id* arrives.

        Non-matching messages (events or other responses) are buffered.
        """
        assert self._ws is not None
        deadline = time.monotonic() + timeout
        while True:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise CDPTimeoutError(
                    f"command {cmd_id} timed out after {timeout}s",
                    timeout=timeout,
                )
            try:
                raw = self._ws.recv(timeout=remaining)
            except _WebSocketTimeoutError as exc:
                raise CDPTimeoutError(
                    f"command {cmd_id} timed out after {timeout}s",
                    timeout=timeout,
                ) from exc

            msg = json.loads(raw)
            if msg.get("id") == cmd_id:
                if "error" in msg:
                    err = msg["error"]
                    raise CDPProtocolError(
                        err.get("code", -1),
                        err.get("message", "unknown error"),
                        data=err.get("data"),
                    )
                return msg.get("result", {})
            # Not our response -- buffer it
            self._event_buffer.append(msg)

    def _wait_for_event(
        self,
        event_name: str,
        *,
        session_id: str | None = None,
        timeout: float,
    ) -> dict:
        """Wait for a specific CDP event.

        First checks the event buffer, then reads from the WebSocket.
        """
        assert self._ws is not None
        # Check buffer first
        for i, msg in enumerate(self._event_buffer):
            if self._matches_event(msg, event_name, session_id):
                del self._event_buffer[i]
                return msg.get("params", {})

        deadline = time.monotonic() + timeout
        while True:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise CDPTimeoutError(
                    f"event {event_name} timed out after {timeout}s",
                    timeout=timeout,
                )
            try:
                raw = self._ws.recv(timeout=remaining)
            except _WebSocketTimeoutError as exc:
                raise CDPTimeoutError(
                    f"event {event_name} timed out after {timeout}s",
                    timeout=timeout,
                ) from exc

            msg = json.loads(raw)
            if self._matches_event(msg, event_name, session_id):
                return msg.get("params", {})
            self._event_buffer.append(msg)

    @staticmethod
    def _matches_event(
        msg: dict,
        event_name: str,
        session_id: str | None,
    ) -> bool:
        """Check if a message matches the expected event."""
        if msg.get("method") != event_name:
            return False
        if session_id is not None and msg.get("sessionId") != session_id:
            return False
        return True

    @staticmethod
    def _resolve_ws_url(url: str, *, timeout: float) -> str:
        """Resolve the browser's debugger WebSocket URL.

        If the URL already has a path (e.g. ``/devtools/browser/...``),
        return it as-is. Otherwise, query the ``/json/version`` endpoint
        to discover the WebSocket debugger URL.
        """
        import urllib.parse

        parsed = urllib.parse.urlparse(url)
        if parsed.path and parsed.path != "/":
            return url

        # Auto-discover via /json/version
        host = parsed.hostname or "localhost"
        port = parsed.port or 9222
        http_url = f"http://{host}:{port}/json/version"

        import http.client

        try:
            conn = http.client.HTTPConnection(host, port, timeout=timeout)
            conn.request("GET", "/json/version")
            resp = conn.getresponse()
            data = json.loads(resp.read())
            conn.close()
            ws_url = data.get("webSocketDebuggerUrl", "")
            if ws_url:
                logger.debug("auto-discovered CDP endpoint: %s", ws_url)
                return ws_url
        except Exception:
            logger.debug(
                "failed to auto-discover CDP endpoint from %s",
                http_url,
                exc_info=True,
            )

        return url

connect(*, timeout=None)

Open the WebSocket connection to the CDP endpoint.

Parameters:

Name Type Description Default
timeout float | None

Connection timeout in seconds. Defaults to the client's default timeout.

None

Raises:

Type Description
CDPConnectionError

If the connection fails.

ImportError

If the websocket module is not available.

Source code in cdp/cdp.py
def connect(self, *, timeout: float | None = None) -> None:
    """Open the WebSocket connection to the CDP endpoint.

    Args:
        timeout: Connection timeout in seconds. Defaults to the
            client's default timeout.

    Raises:
        CDPConnectionError: If the connection fails.
        ImportError: If the websocket module is not available.
    """
    if self._ws is not None:
        return

    if not _HAS_WEBSOCKET:
        raise ImportError(
            "cdp module requires sibling 'websocket' module; "
            "install it with: zerodep add websocket"
        )

    ws_url = self._resolve_ws_url(self._url, timeout=timeout or self._timeout)

    try:
        ws = _WebSocketClient(ws_url)
        ws.connect(timeout=timeout or self._timeout)
        self._ws = ws
    except _WebSocketConnectionError as exc:
        raise CDPConnectionError(
            f"failed to connect to CDP endpoint: {exc}",
            url=ws_url,
        ) from exc
    except _WebSocketTimeoutError as exc:
        raise CDPTimeoutError(
            f"connection to CDP endpoint timed out: {exc}",
            timeout=timeout or self._timeout,
        ) from exc

send_command(method, params=None, *, session_id=None, timeout=None)

Send a CDP command and wait for the response.

Parameters:

Name Type Description Default
method str

CDP method name (e.g. Page.navigate).

required
params dict | None

Optional command parameters.

None
session_id str | None

Optional session ID for target-specific commands.

None
timeout float | None

Command timeout in seconds.

None

Returns:

Type Description
dict

The result dict from the CDP response.

Raises:

Type Description
CDPTimeoutError

If the command times out.

CDPProtocolError

If the CDP response contains an error.

CDPError

If not connected.

Source code in cdp/cdp.py
def send_command(
    self,
    method: str,
    params: dict | None = None,
    *,
    session_id: str | None = None,
    timeout: float | None = None,
) -> dict:
    """Send a CDP command and wait for the response.

    Args:
        method: CDP method name (e.g. ``Page.navigate``).
        params: Optional command parameters.
        session_id: Optional session ID for target-specific commands.
        timeout: Command timeout in seconds.

    Returns:
        The ``result`` dict from the CDP response.

    Raises:
        CDPTimeoutError: If the command times out.
        CDPProtocolError: If the CDP response contains an error.
        CDPError: If not connected.
    """
    self._ensure_connected()
    assert self._ws is not None

    cmd_id = next(self._cmd_id)
    msg: dict = {"id": cmd_id, "method": method}
    if params:
        msg["params"] = params
    if session_id:
        msg["sessionId"] = session_id

    self._ws.send(json.dumps(msg))
    return self._recv_response(cmd_id, timeout=timeout or self._timeout)

create_target(url='about:blank')

Create a new browser target (tab) and attach to it.

Parameters:

Name Type Description Default
url str

Initial URL to load in the new target.

'about:blank'

Returns:

Type Description
str

The target ID.

Source code in cdp/cdp.py
def create_target(self, url: str = "about:blank") -> str:
    """Create a new browser target (tab) and attach to it.

    Args:
        url: Initial URL to load in the new target.

    Returns:
        The target ID.
    """
    result = self.send_command("Target.createTarget", {"url": url})
    target_id = result["targetId"]

    attach_result = self.send_command(
        "Target.attachToTarget",
        {"targetId": target_id, "flatten": True},
    )
    session_id = attach_result["sessionId"]
    self._targets[target_id] = session_id
    logger.debug("created target %s with session %s", target_id, session_id)
    return target_id

close_target(target_id)

Close a browser target (tab).

Parameters:

Name Type Description Default
target_id str

The target ID to close.

required
Source code in cdp/cdp.py
def close_target(self, target_id: str) -> None:
    """Close a browser target (tab).

    Args:
        target_id: The target ID to close.
    """
    if target_id not in self._targets:
        return
    try:
        self.send_command("Target.closeTarget", {"targetId": target_id})
    except CDPError:
        logger.debug("failed to close target %s", target_id, exc_info=True)
    self._targets.pop(target_id, None)

navigate(target_id, url, *, timeout=None)

Navigate a target to a URL and wait for the page to load.

Parameters:

Name Type Description Default
target_id str

The target ID.

required
url str

URL to navigate to.

required
timeout float | None

Page load timeout in seconds.

None
Source code in cdp/cdp.py
def navigate(
    self,
    target_id: str,
    url: str,
    *,
    timeout: float | None = None,
) -> None:
    """Navigate a target to a URL and wait for the page to load.

    Args:
        target_id: The target ID.
        url: URL to navigate to.
        timeout: Page load timeout in seconds.
    """
    session_id = self._get_session_id(target_id)
    load_timeout = timeout or DEFAULT_PAGE_LOAD_TIMEOUT

    self.send_command("Page.enable", session_id=session_id)
    self.send_command("Page.navigate", {"url": url}, session_id=session_id)
    self._wait_for_event(
        "Page.loadEventFired",
        session_id=session_id,
        timeout=load_timeout,
    )

wait_for_load(target_id, *, timeout=None)

Wait for a target's page to finish loading.

Parameters:

Name Type Description Default
target_id str

The target ID.

required
timeout float | None

Page load timeout in seconds.

None
Source code in cdp/cdp.py
def wait_for_load(
    self,
    target_id: str,
    *,
    timeout: float | None = None,
) -> None:
    """Wait for a target's page to finish loading.

    Args:
        target_id: The target ID.
        timeout: Page load timeout in seconds.
    """
    session_id = self._get_session_id(target_id)
    self.send_command("Page.enable", session_id=session_id)
    self._wait_for_event(
        "Page.loadEventFired",
        session_id=session_id,
        timeout=timeout or DEFAULT_PAGE_LOAD_TIMEOUT,
    )

evaluate(target_id, expression)

Evaluate a JavaScript expression in a target.

Parameters:

Name Type Description Default
target_id str

The target ID.

required
expression str

JavaScript expression to evaluate.

required

Returns:

Type Description
object

The result value.

Raises:

Type Description
CDPProtocolError

If the evaluation throws an exception.

Source code in cdp/cdp.py
def evaluate(self, target_id: str, expression: str) -> object:
    """Evaluate a JavaScript expression in a target.

    Args:
        target_id: The target ID.
        expression: JavaScript expression to evaluate.

    Returns:
        The result value.

    Raises:
        CDPProtocolError: If the evaluation throws an exception.
    """
    session_id = self._get_session_id(target_id)
    result = self.send_command(
        "Runtime.evaluate",
        {"expression": expression, "returnByValue": True},
        session_id=session_id,
    )

    if "exceptionDetails" in result:
        exc_details = result["exceptionDetails"]
        text = exc_details.get("text", "evaluation failed")
        raise CDPProtocolError(-1, text)

    return result.get("result", {}).get("value")

get_rendered_text(url, *, timeout=None)

Navigate to a URL and extract the rendered text content.

Creates a temporary target, navigates to the URL, waits for load, extracts document.body.innerText, and closes the target.

Parameters:

Name Type Description Default
url str

URL to render.

required
timeout float | None

Page load timeout in seconds.

None

Returns:

Type Description
str

The rendered text content of the page.

Source code in cdp/cdp.py
def get_rendered_text(
    self,
    url: str,
    *,
    timeout: float | None = None,
) -> str:
    """Navigate to a URL and extract the rendered text content.

    Creates a temporary target, navigates to the URL, waits for load,
    extracts ``document.body.innerText``, and closes the target.

    Args:
        url: URL to render.
        timeout: Page load timeout in seconds.

    Returns:
        The rendered text content of the page.
    """
    target_id = self.create_target()
    try:
        self.navigate(target_id, url, timeout=timeout)
        result = self.evaluate(target_id, "document.body.innerText")
        return result if isinstance(result, str) else str(result or "")
    finally:
        self.close_target(target_id)

get_rendered_html(url, *, timeout=None)

Navigate to a URL and extract the rendered HTML.

Creates a temporary target, navigates to the URL, waits for load, extracts document.documentElement.outerHTML, and closes the target.

Parameters:

Name Type Description Default
url str

URL to render.

required
timeout float | None

Page load timeout in seconds.

None

Returns:

Type Description
str

The rendered outer HTML of the page.

Source code in cdp/cdp.py
def get_rendered_html(
    self,
    url: str,
    *,
    timeout: float | None = None,
) -> str:
    """Navigate to a URL and extract the rendered HTML.

    Creates a temporary target, navigates to the URL, waits for load,
    extracts ``document.documentElement.outerHTML``, and closes the target.

    Args:
        url: URL to render.
        timeout: Page load timeout in seconds.

    Returns:
        The rendered outer HTML of the page.
    """
    target_id = self.create_target()
    try:
        self.navigate(target_id, url, timeout=timeout)
        result = self.evaluate(target_id, "document.documentElement.outerHTML")
        return result if isinstance(result, str) else str(result or "")
    finally:
        self.close_target(target_id)

set_user_agent(target_id, user_agent)

Override the User-Agent for a target.

Parameters:

Name Type Description Default
target_id str

The target ID.

required
user_agent str

The User-Agent string to set.

required
Source code in cdp/cdp.py
def set_user_agent(self, target_id: str, user_agent: str) -> None:
    """Override the User-Agent for a target.

    Args:
        target_id: The target ID.
        user_agent: The User-Agent string to set.
    """
    session_id = self._get_session_id(target_id)
    self.send_command(
        "Network.setUserAgentOverride",
        {"userAgent": user_agent},
        session_id=session_id,
    )

close()

Close all targets and the WebSocket connection.

Source code in cdp/cdp.py
def close(self) -> None:
    """Close all targets and the WebSocket connection."""
    if self._ws is None:
        return

    # Close all targets (best-effort)
    for target_id in list(self._targets):
        try:
            self.send_command("Target.closeTarget", {"targetId": target_id})
        except (CDPError, _WebSocketError):
            pass
    self._targets.clear()
    self._event_buffer.clear()

    try:
        self._ws.close()
    except _WebSocketError:
        pass
    self._ws = None

AsyncCDPClient

Asynchronous Chrome DevTools Protocol client.

Parameters:

Name Type Description Default
url str

CDP WebSocket endpoint URL (e.g. ws://localhost:9222).

required
timeout float

Default timeout for CDP commands in seconds.

DEFAULT_TIMEOUT

Example::

async with AsyncCDPClient("ws://localhost:9222") as client:
    text = await client.get_rendered_text("https://example.com")
    print(text)
Source code in cdp/cdp.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
class AsyncCDPClient:
    """Asynchronous Chrome DevTools Protocol client.

    Args:
        url: CDP WebSocket endpoint URL (e.g. ``ws://localhost:9222``).
        timeout: Default timeout for CDP commands in seconds.

    Example::

        async with AsyncCDPClient("ws://localhost:9222") as client:
            text = await client.get_rendered_text("https://example.com")
            print(text)
    """

    def __init__(
        self,
        url: str,
        *,
        timeout: float = DEFAULT_TIMEOUT,
    ) -> None:
        self._url = url
        self._timeout = timeout
        self._ws: _AsyncWebSocketClient | None = None
        self._cmd_id = itertools.count(1)
        self._targets: dict[str, str] = {}
        self._event_buffer: collections.deque[dict] = collections.deque()

    async def connect(self, *, timeout: float | None = None) -> None:
        """Open the WebSocket connection to the CDP endpoint.

        Args:
            timeout: Connection timeout in seconds.

        Raises:
            CDPConnectionError: If the connection fails.
            ImportError: If the websocket module is not available.
        """
        if self._ws is not None:
            return

        if not _HAS_WEBSOCKET:
            raise ImportError(
                "cdp module requires sibling 'websocket' module; "
                "install it with: zerodep add websocket"
            )

        ws_url = self._resolve_ws_url(self._url, timeout=timeout or self._timeout)

        try:
            ws = _AsyncWebSocketClient(ws_url)
            await ws.connect(timeout=timeout or self._timeout)
            self._ws = ws
        except _WebSocketConnectionError as exc:
            raise CDPConnectionError(
                f"failed to connect to CDP endpoint: {exc}",
                url=ws_url,
            ) from exc
        except _WebSocketTimeoutError as exc:
            raise CDPTimeoutError(
                f"connection to CDP endpoint timed out: {exc}",
                timeout=timeout or self._timeout,
            ) from exc

    async def send_command(
        self,
        method: str,
        params: dict | None = None,
        *,
        session_id: str | None = None,
        timeout: float | None = None,
    ) -> dict:
        """Send a CDP command and wait for the response.

        Args:
            method: CDP method name.
            params: Optional command parameters.
            session_id: Optional session ID for target-specific commands.
            timeout: Command timeout in seconds.

        Returns:
            The ``result`` dict from the CDP response.
        """
        self._ensure_connected()
        assert self._ws is not None

        cmd_id = next(self._cmd_id)
        msg: dict = {"id": cmd_id, "method": method}
        if params:
            msg["params"] = params
        if session_id:
            msg["sessionId"] = session_id

        await self._ws.send(json.dumps(msg))
        return await self._recv_response(cmd_id, timeout=timeout or self._timeout)

    async def create_target(self, url: str = "about:blank") -> str:
        """Create a new browser target (tab) and attach to it.

        Args:
            url: Initial URL to load in the new target.

        Returns:
            The target ID.
        """
        result = await self.send_command("Target.createTarget", {"url": url})
        target_id = result["targetId"]

        attach_result = await self.send_command(
            "Target.attachToTarget",
            {"targetId": target_id, "flatten": True},
        )
        session_id = attach_result["sessionId"]
        self._targets[target_id] = session_id
        logger.debug("created target %s with session %s", target_id, session_id)
        return target_id

    async def close_target(self, target_id: str) -> None:
        """Close a browser target (tab).

        Args:
            target_id: The target ID to close.
        """
        if target_id not in self._targets:
            return
        try:
            await self.send_command("Target.closeTarget", {"targetId": target_id})
        except CDPError:
            logger.debug("failed to close target %s", target_id, exc_info=True)
        self._targets.pop(target_id, None)

    async def navigate(
        self,
        target_id: str,
        url: str,
        *,
        timeout: float | None = None,
    ) -> None:
        """Navigate a target to a URL and wait for the page to load.

        Args:
            target_id: The target ID.
            url: URL to navigate to.
            timeout: Page load timeout in seconds.
        """
        session_id = self._get_session_id(target_id)
        load_timeout = timeout or DEFAULT_PAGE_LOAD_TIMEOUT

        await self.send_command("Page.enable", session_id=session_id)
        await self.send_command("Page.navigate", {"url": url}, session_id=session_id)
        await self._wait_for_event(
            "Page.loadEventFired",
            session_id=session_id,
            timeout=load_timeout,
        )

    async def wait_for_load(
        self,
        target_id: str,
        *,
        timeout: float | None = None,
    ) -> None:
        """Wait for a target's page to finish loading.

        Args:
            target_id: The target ID.
            timeout: Page load timeout in seconds.
        """
        session_id = self._get_session_id(target_id)
        await self.send_command("Page.enable", session_id=session_id)
        await self._wait_for_event(
            "Page.loadEventFired",
            session_id=session_id,
            timeout=timeout or DEFAULT_PAGE_LOAD_TIMEOUT,
        )

    async def evaluate(self, target_id: str, expression: str) -> object:
        """Evaluate a JavaScript expression in a target.

        Args:
            target_id: The target ID.
            expression: JavaScript expression to evaluate.

        Returns:
            The result value.

        Raises:
            CDPProtocolError: If the evaluation throws an exception.
        """
        session_id = self._get_session_id(target_id)
        result = await self.send_command(
            "Runtime.evaluate",
            {"expression": expression, "returnByValue": True},
            session_id=session_id,
        )

        if "exceptionDetails" in result:
            exc_details = result["exceptionDetails"]
            text = exc_details.get("text", "evaluation failed")
            raise CDPProtocolError(-1, text)

        return result.get("result", {}).get("value")

    async def get_rendered_text(
        self,
        url: str,
        *,
        timeout: float | None = None,
    ) -> str:
        """Navigate to a URL and extract the rendered text content.

        Args:
            url: URL to render.
            timeout: Page load timeout in seconds.

        Returns:
            The rendered text content of the page.
        """
        target_id = await self.create_target()
        try:
            await self.navigate(target_id, url, timeout=timeout)
            result = await self.evaluate(target_id, "document.body.innerText")
            return result if isinstance(result, str) else str(result or "")
        finally:
            await self.close_target(target_id)

    async def get_rendered_html(
        self,
        url: str,
        *,
        timeout: float | None = None,
    ) -> str:
        """Navigate to a URL and extract the rendered HTML.

        Args:
            url: URL to render.
            timeout: Page load timeout in seconds.

        Returns:
            The rendered outer HTML of the page.
        """
        target_id = await self.create_target()
        try:
            await self.navigate(target_id, url, timeout=timeout)
            result = await self.evaluate(
                target_id, "document.documentElement.outerHTML"
            )
            return result if isinstance(result, str) else str(result or "")
        finally:
            await self.close_target(target_id)

    async def set_user_agent(self, target_id: str, user_agent: str) -> None:
        """Override the User-Agent for a target.

        Args:
            target_id: The target ID.
            user_agent: The User-Agent string to set.
        """
        session_id = self._get_session_id(target_id)
        await self.send_command(
            "Network.setUserAgentOverride",
            {"userAgent": user_agent},
            session_id=session_id,
        )

    async def close(self) -> None:
        """Close all targets and the WebSocket connection."""
        if self._ws is None:
            return

        for target_id in list(self._targets):
            try:
                await self.send_command("Target.closeTarget", {"targetId": target_id})
            except (CDPError, _WebSocketError):
                pass
        self._targets.clear()
        self._event_buffer.clear()

        try:
            await self._ws.close()
        except _WebSocketError:
            pass
        self._ws = None

    async def __aenter__(self) -> AsyncCDPClient:
        await self.connect()
        return self

    async def __aexit__(self, *args: object) -> None:
        await self.close()

    # ── Async internal helpers ──

    def _ensure_connected(self) -> None:
        if self._ws is None:
            raise CDPError("not connected")

    def _get_session_id(self, target_id: str) -> str:
        session_id = self._targets.get(target_id)
        if session_id is None:
            raise CDPError(f"unknown target: {target_id}")
        return session_id

    async def _recv_response(self, cmd_id: int, *, timeout: float) -> dict:
        """Receive messages until the response matching *cmd_id* arrives."""
        assert self._ws is not None
        deadline = time.monotonic() + timeout
        while True:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise CDPTimeoutError(
                    f"command {cmd_id} timed out after {timeout}s",
                    timeout=timeout,
                )
            try:
                raw = await self._ws.recv(timeout=remaining)
            except _WebSocketTimeoutError as exc:
                raise CDPTimeoutError(
                    f"command {cmd_id} timed out after {timeout}s",
                    timeout=timeout,
                ) from exc

            msg = json.loads(raw)
            if msg.get("id") == cmd_id:
                if "error" in msg:
                    err = msg["error"]
                    raise CDPProtocolError(
                        err.get("code", -1),
                        err.get("message", "unknown error"),
                        data=err.get("data"),
                    )
                return msg.get("result", {})
            self._event_buffer.append(msg)

    async def _wait_for_event(
        self,
        event_name: str,
        *,
        session_id: str | None = None,
        timeout: float,
    ) -> dict:
        """Wait for a specific CDP event."""
        assert self._ws is not None
        # Check buffer first
        for i, msg in enumerate(self._event_buffer):
            if self._matches_event(msg, event_name, session_id):
                del self._event_buffer[i]
                return msg.get("params", {})

        deadline = time.monotonic() + timeout
        while True:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise CDPTimeoutError(
                    f"event {event_name} timed out after {timeout}s",
                    timeout=timeout,
                )
            try:
                raw = await self._ws.recv(timeout=remaining)
            except _WebSocketTimeoutError as exc:
                raise CDPTimeoutError(
                    f"event {event_name} timed out after {timeout}s",
                    timeout=timeout,
                ) from exc

            msg = json.loads(raw)
            if self._matches_event(msg, event_name, session_id):
                return msg.get("params", {})
            self._event_buffer.append(msg)

    @staticmethod
    def _matches_event(
        msg: dict,
        event_name: str,
        session_id: str | None,
    ) -> bool:
        """Check if a message matches the expected event."""
        if msg.get("method") != event_name:
            return False
        if session_id is not None and msg.get("sessionId") != session_id:
            return False
        return True

    @staticmethod
    def _resolve_ws_url(url: str, *, timeout: float) -> str:
        """Resolve the browser's debugger WebSocket URL."""
        # Reuse the sync implementation
        return CDPClient._resolve_ws_url(url, timeout=timeout)

connect(*, timeout=None) async

Open the WebSocket connection to the CDP endpoint.

Parameters:

Name Type Description Default
timeout float | None

Connection timeout in seconds.

None

Raises:

Type Description
CDPConnectionError

If the connection fails.

ImportError

If the websocket module is not available.

Source code in cdp/cdp.py
async def connect(self, *, timeout: float | None = None) -> None:
    """Open the WebSocket connection to the CDP endpoint.

    Args:
        timeout: Connection timeout in seconds.

    Raises:
        CDPConnectionError: If the connection fails.
        ImportError: If the websocket module is not available.
    """
    if self._ws is not None:
        return

    if not _HAS_WEBSOCKET:
        raise ImportError(
            "cdp module requires sibling 'websocket' module; "
            "install it with: zerodep add websocket"
        )

    ws_url = self._resolve_ws_url(self._url, timeout=timeout or self._timeout)

    try:
        ws = _AsyncWebSocketClient(ws_url)
        await ws.connect(timeout=timeout or self._timeout)
        self._ws = ws
    except _WebSocketConnectionError as exc:
        raise CDPConnectionError(
            f"failed to connect to CDP endpoint: {exc}",
            url=ws_url,
        ) from exc
    except _WebSocketTimeoutError as exc:
        raise CDPTimeoutError(
            f"connection to CDP endpoint timed out: {exc}",
            timeout=timeout or self._timeout,
        ) from exc

send_command(method, params=None, *, session_id=None, timeout=None) async

Send a CDP command and wait for the response.

Parameters:

Name Type Description Default
method str

CDP method name.

required
params dict | None

Optional command parameters.

None
session_id str | None

Optional session ID for target-specific commands.

None
timeout float | None

Command timeout in seconds.

None

Returns:

Type Description
dict

The result dict from the CDP response.

Source code in cdp/cdp.py
async def send_command(
    self,
    method: str,
    params: dict | None = None,
    *,
    session_id: str | None = None,
    timeout: float | None = None,
) -> dict:
    """Send a CDP command and wait for the response.

    Args:
        method: CDP method name.
        params: Optional command parameters.
        session_id: Optional session ID for target-specific commands.
        timeout: Command timeout in seconds.

    Returns:
        The ``result`` dict from the CDP response.
    """
    self._ensure_connected()
    assert self._ws is not None

    cmd_id = next(self._cmd_id)
    msg: dict = {"id": cmd_id, "method": method}
    if params:
        msg["params"] = params
    if session_id:
        msg["sessionId"] = session_id

    await self._ws.send(json.dumps(msg))
    return await self._recv_response(cmd_id, timeout=timeout or self._timeout)

create_target(url='about:blank') async

Create a new browser target (tab) and attach to it.

Parameters:

Name Type Description Default
url str

Initial URL to load in the new target.

'about:blank'

Returns:

Type Description
str

The target ID.

Source code in cdp/cdp.py
async def create_target(self, url: str = "about:blank") -> str:
    """Create a new browser target (tab) and attach to it.

    Args:
        url: Initial URL to load in the new target.

    Returns:
        The target ID.
    """
    result = await self.send_command("Target.createTarget", {"url": url})
    target_id = result["targetId"]

    attach_result = await self.send_command(
        "Target.attachToTarget",
        {"targetId": target_id, "flatten": True},
    )
    session_id = attach_result["sessionId"]
    self._targets[target_id] = session_id
    logger.debug("created target %s with session %s", target_id, session_id)
    return target_id

close_target(target_id) async

Close a browser target (tab).

Parameters:

Name Type Description Default
target_id str

The target ID to close.

required
Source code in cdp/cdp.py
async def close_target(self, target_id: str) -> None:
    """Close a browser target (tab).

    Args:
        target_id: The target ID to close.
    """
    if target_id not in self._targets:
        return
    try:
        await self.send_command("Target.closeTarget", {"targetId": target_id})
    except CDPError:
        logger.debug("failed to close target %s", target_id, exc_info=True)
    self._targets.pop(target_id, None)

navigate(target_id, url, *, timeout=None) async

Navigate a target to a URL and wait for the page to load.

Parameters:

Name Type Description Default
target_id str

The target ID.

required
url str

URL to navigate to.

required
timeout float | None

Page load timeout in seconds.

None
Source code in cdp/cdp.py
async def navigate(
    self,
    target_id: str,
    url: str,
    *,
    timeout: float | None = None,
) -> None:
    """Navigate a target to a URL and wait for the page to load.

    Args:
        target_id: The target ID.
        url: URL to navigate to.
        timeout: Page load timeout in seconds.
    """
    session_id = self._get_session_id(target_id)
    load_timeout = timeout or DEFAULT_PAGE_LOAD_TIMEOUT

    await self.send_command("Page.enable", session_id=session_id)
    await self.send_command("Page.navigate", {"url": url}, session_id=session_id)
    await self._wait_for_event(
        "Page.loadEventFired",
        session_id=session_id,
        timeout=load_timeout,
    )

wait_for_load(target_id, *, timeout=None) async

Wait for a target's page to finish loading.

Parameters:

Name Type Description Default
target_id str

The target ID.

required
timeout float | None

Page load timeout in seconds.

None
Source code in cdp/cdp.py
async def wait_for_load(
    self,
    target_id: str,
    *,
    timeout: float | None = None,
) -> None:
    """Wait for a target's page to finish loading.

    Args:
        target_id: The target ID.
        timeout: Page load timeout in seconds.
    """
    session_id = self._get_session_id(target_id)
    await self.send_command("Page.enable", session_id=session_id)
    await self._wait_for_event(
        "Page.loadEventFired",
        session_id=session_id,
        timeout=timeout or DEFAULT_PAGE_LOAD_TIMEOUT,
    )

evaluate(target_id, expression) async

Evaluate a JavaScript expression in a target.

Parameters:

Name Type Description Default
target_id str

The target ID.

required
expression str

JavaScript expression to evaluate.

required

Returns:

Type Description
object

The result value.

Raises:

Type Description
CDPProtocolError

If the evaluation throws an exception.

Source code in cdp/cdp.py
async def evaluate(self, target_id: str, expression: str) -> object:
    """Evaluate a JavaScript expression in a target.

    Args:
        target_id: The target ID.
        expression: JavaScript expression to evaluate.

    Returns:
        The result value.

    Raises:
        CDPProtocolError: If the evaluation throws an exception.
    """
    session_id = self._get_session_id(target_id)
    result = await self.send_command(
        "Runtime.evaluate",
        {"expression": expression, "returnByValue": True},
        session_id=session_id,
    )

    if "exceptionDetails" in result:
        exc_details = result["exceptionDetails"]
        text = exc_details.get("text", "evaluation failed")
        raise CDPProtocolError(-1, text)

    return result.get("result", {}).get("value")

get_rendered_text(url, *, timeout=None) async

Navigate to a URL and extract the rendered text content.

Parameters:

Name Type Description Default
url str

URL to render.

required
timeout float | None

Page load timeout in seconds.

None

Returns:

Type Description
str

The rendered text content of the page.

Source code in cdp/cdp.py
async def get_rendered_text(
    self,
    url: str,
    *,
    timeout: float | None = None,
) -> str:
    """Navigate to a URL and extract the rendered text content.

    Args:
        url: URL to render.
        timeout: Page load timeout in seconds.

    Returns:
        The rendered text content of the page.
    """
    target_id = await self.create_target()
    try:
        await self.navigate(target_id, url, timeout=timeout)
        result = await self.evaluate(target_id, "document.body.innerText")
        return result if isinstance(result, str) else str(result or "")
    finally:
        await self.close_target(target_id)

get_rendered_html(url, *, timeout=None) async

Navigate to a URL and extract the rendered HTML.

Parameters:

Name Type Description Default
url str

URL to render.

required
timeout float | None

Page load timeout in seconds.

None

Returns:

Type Description
str

The rendered outer HTML of the page.

Source code in cdp/cdp.py
async def get_rendered_html(
    self,
    url: str,
    *,
    timeout: float | None = None,
) -> str:
    """Navigate to a URL and extract the rendered HTML.

    Args:
        url: URL to render.
        timeout: Page load timeout in seconds.

    Returns:
        The rendered outer HTML of the page.
    """
    target_id = await self.create_target()
    try:
        await self.navigate(target_id, url, timeout=timeout)
        result = await self.evaluate(
            target_id, "document.documentElement.outerHTML"
        )
        return result if isinstance(result, str) else str(result or "")
    finally:
        await self.close_target(target_id)

set_user_agent(target_id, user_agent) async

Override the User-Agent for a target.

Parameters:

Name Type Description Default
target_id str

The target ID.

required
user_agent str

The User-Agent string to set.

required
Source code in cdp/cdp.py
async def set_user_agent(self, target_id: str, user_agent: str) -> None:
    """Override the User-Agent for a target.

    Args:
        target_id: The target ID.
        user_agent: The User-Agent string to set.
    """
    session_id = self._get_session_id(target_id)
    await self.send_command(
        "Network.setUserAgentOverride",
        {"userAgent": user_agent},
        session_id=session_id,
    )

close() async

Close all targets and the WebSocket connection.

Source code in cdp/cdp.py
async def close(self) -> None:
    """Close all targets and the WebSocket connection."""
    if self._ws is None:
        return

    for target_id in list(self._targets):
        try:
            await self.send_command("Target.closeTarget", {"targetId": target_id})
        except (CDPError, _WebSocketError):
            pass
    self._targets.clear()
    self._event_buffer.clear()

    try:
        await self._ws.close()
    except _WebSocketError:
        pass
    self._ws = None