cdp-socket is a Python library designed for programmatically interacting with the Chrome DevTools Protocol (CDP). It provides a high-level asynchronous API to control Chrome-based browsers, enabling tasks such as browser automation, scraping, and debugging. The library is currently at version 1.2.8, with its last release in April 2024, indicating active maintenance and a regular, albeit not fixed, release cadence.
pip install cdp-socketVerified import paths — ran on the pinned version, not inferred.
This quickstart launches a headless Chrome instance, connects to its DevTools Protocol WebSocket, retrieves active targets, and then gracefully closes the browser. It includes setup for a temporary data directory and clean-up. Ensure a Chrome-based browser is installed on your system.
Ensure Chrome or Chromium is installed. On Linux, verify `google-chrome` or `chromium-browser` is in PATH. On Windows/macOS, ensure the default installation path is used or add it to PATH.
After launching Chrome, retrieve available targets using `Target.getTargets()`. Identify the correct `webSocketDebuggerUrl` for the specific page or context you intend to control. For page-specific operations, ensure you're connecting to a page target's WebSocket URL.
Always `await` calls to `SingleCDPSocket` methods and `get_websock_url` within an `async` function. Run the main asynchronous function using `asyncio.run()`.
Ensure `os.kill(process.pid, 15)` is called in a `finally` block to guarantee the Chrome process is terminated even if errors occur. Also, consider removing the temporary data directory with `shutil.rmtree()`.
Verify that Chrome is installed and runnable. Check the logs for `launch_chrome` to see if it printed any errors. Increase the `timeout` parameter for `get_websock_url` and `SingleCDPSocket` if running on a slower system.
First, use `Target.getTargets()` to list all available targets. Identify the 'page' target's WebSocket URL. You may need to create a new `SingleCDPSocket` instance connected to that specific page URL if you're not already, or ensure your initial connection is to a page target if that's your intent. The `sock.exec` method can target specific sessions using a `sessionId` if you attach to a target.