{"id":8006,"library":"cdp-socket","title":"CDP Socket","description":"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.","status":"active","version":"1.2.8","language":"en","source_language":"en","source_url":"https://github.com/kaliiiiiiiiii/CDP-Socket","tags":["chrome-devtools","cdp","browser-automation","asyncio","scraping"],"install":[{"cmd":"pip install cdp-socket","lang":"bash","label":"Install with pip"}],"dependencies":[{"reason":"Runtime environment","package":"Python","optional":false},{"reason":"Required for Chrome DevTools Protocol communication","package":"Chrome-Browser","optional":false}],"imports":[{"symbol":"SingleCDPSocket","correct":"from cdp_socket.socket import SingleCDPSocket"},{"symbol":"launch_chrome","correct":"from cdp_socket.utils.utils import launch_chrome"},{"symbol":"random_port","correct":"from cdp_socket.utils.utils import random_port"},{"symbol":"get_websock_url","correct":"from cdp_socket.utils.conn import get_websock_url"}],"quickstart":{"code":"import asyncio\nimport os\nimport shutil\nfrom cdp_socket.utils.utils import launch_chrome, random_port\nfrom cdp_socket.utils.conn import get_websock_url\nfrom cdp_socket.socket import SingleCDPSocket\n\nasync def main():\n    data_dir = os.path.join(os.getcwd(), \"cdp_data_dir\")\n    port = random_port()\n    process = None\n    try:\n        process = launch_chrome(data_dir, port)\n        websock_url = await get_websock_url(port, timeout=5)\n        async with SingleCDPSocket(websock_url, timeout=5) as sock:\n            targets = await sock.exec(\"Target.getTargets\")\n            print(f\"Active targets: {targets}\")\n            # Example: Navigate to a page\n            # This assumes you have a page target. The 'Target.getTargets' output helps identify it.\n            # For browser-level commands, you directly use the 'sock' object.\n            # For page-specific commands, you might need to attach to a page target first.\n            # For simplicity, this example just fetches targets.\n    except Exception as e:\n        print(f\"An error occurred: {e}\")\n    finally:\n        if process and process.poll() is None: # Check if process is still running\n            os.kill(process.pid, 15) # Terminate Chrome gracefully\n        if os.path.exists(data_dir):\n            shutil.rmtree(data_dir)\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n","lang":"python","description":"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."},"warnings":[{"fix":"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.","message":"Chrome/Chromium browser must be installed and accessible in the system's PATH, or its path explicitly provided to `launch_chrome`. If the browser is not found, `launch_chrome` will fail.","severity":"gotcha","affected_versions":"All"},{"fix":"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.","message":"Connecting to the wrong CDP endpoint (e.g., browser-level vs. page-level) will cause commands to fail with 'command not found' or 'invalid session ID' errors. Browser-level commands require a browser target, while DOM/Page/Network commands require a page target.","severity":"breaking","affected_versions":"All"},{"fix":"Always `await` calls to `SingleCDPSocket` methods and `get_websock_url` within an `async` function. Run the main asynchronous function using `asyncio.run()`.","message":"As `cdp-socket` is an asynchronous library, operations must be awaited within an `async` function. Improper handling of `await` calls will lead to `RuntimeWarning: coroutine '...' was never awaited` or blocks in execution.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"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()`.","cause":"The `launch_chrome` function or subsequent operations are not correctly terminating the Chrome browser process, leading to orphaned processes and resource leaks.","error":"RuntimeWarning: Enable tracemalloc to get the object allocation traceback"},{"fix":"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.","cause":"The Chrome browser did not start correctly, or the remote debugging port was not exposed, or the connection attempt timed out.","error":"cdp_socket.utils.conn.WebSocketConnectionError: Failed to connect to websocket url ... after ... seconds"},{"fix":"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.","cause":"You are attempting to use a page-specific command (like 'Page.navigate') on a browser-level target, or vice-versa. Some commands are scoped to the overall browser, while others are specific to a particular page or execution context.","error":"await sock.exec(\"Page.navigate\", {\"url\": \"https://example.com\"}) resulted in an error like 'Target.navigate' was not found."}]}