CDP-Use: Chrome DevTools Protocol Client
CDP-Use is a type-safe Python client library for the Chrome DevTools Protocol (CDP). It provides auto-generated, strongly-typed commands and events, allowing for interaction with browsers like Chrome and Edge, or browser automation tools like Playwright and Puppeteer. It is actively maintained with regular releases, currently at version 1.4.5.
Warnings
- breaking The library was renamed from `cdp-py` to `cdp-use` starting with version 1.0.0. All previous imports (`from cdp_py import ...`) and parts of the API surface are incompatible with `cdp-use`.
- gotcha CDP-Use connects to an existing Chrome DevTools Protocol endpoint. You must have a browser (Chrome, Edge, Playwright-launched, etc.) running with remote debugging enabled and accessible at the specified `Target` URL.
- gotcha The `CDP` client is an asynchronous context manager. It's crucial to use it within an `async with` statement to ensure proper connection establishment and graceful closure of the WebSocket connection.
Install
-
pip install cdp-use
Imports
- CDP
from cdp_use import CDP
- Target
from cdp_use.target import Target
Quickstart
import asyncio
from cdp_use import CDP
from cdp_use.target import Target
import os
async def main():
# Ensure Chrome/Edge is running with --remote-debugging-port=9222
# or connect to a Playwright/Puppeteer launched browser.
# The URL can be an HTTP endpoint ('http://...') or a WebSocket URL ('ws://...')
cdp_url = os.environ.get("CDP_DEBUGGING_URL", "http://127.0.0.1:9222")
async with CDP(Target(cdp_url)) as cdp:
page = cdp.page
await page.enable()
print(f"Navigating to example.com via CDP...")
await page.navigate("https://www.example.com")
# Wait for navigation to complete (e.g., load event)
await page.await_load_event()
current_url = await page.get_navigated_history().result.current_entry.url
print(f"Current URL: {current_url}")
# Example: Get document layout metrics
layout_metrics = await page.get_layout_metrics()
print(f"Document content width: {layout_metrics.content_size.width}")
await asyncio.sleep(2) # Keep the connection alive briefly for inspection
asyncio.run(main())