MyCDP: Autogenerated Chrome DevTools Protocol Client
MyCDP is an autogenerated Python client for the Chrome DevTools Protocol (CDP), providing a direct, low-level interface to control Chrome and Chromium-based browsers. It wraps the latest CDP specification, making it highly synchronized with Chrome's internal API. Current version is 1.3.7, with updates released frequently to reflect changes in CDP.
Warnings
- breaking The enum value `PrivateNetworkRequestPolicy` in the `Network` domain was renamed to `LocalNetworkAccessRequestPolicy` to align with upstream CDP changes.
- gotcha MyCDP is autogenerated directly from the Chrome DevTools Protocol specification. This means its API surface can change significantly with new Chrome releases, potentially introducing breaking changes or requiring updates to your code, even in minor MyCDP versions.
- gotcha MyCDP requires a running Chrome or Chromium browser instance with remote debugging enabled. It does not launch the browser itself by default. You must start the browser separately or manage its lifecycle within your application.
- gotcha Connections to the Chrome DevTools Protocol should always be explicitly closed using `cdp.browser.close(session)` when no longer needed to release resources and prevent potential memory leaks or hanging browser processes.
Install
-
pip install mycdp
Imports
- cdp
from mycdp import cdp
Quickstart
import subprocess
import time
import os
from mycdp import cdp
# --- This quickstart requires a Chrome/Chromium browser executable in your PATH ---
# Start Chrome in headless mode with remote debugging enabled on port 9222
# Adjust 'google-chrome' to 'chromium', 'chrome', or the full path to your browser
chrome_executable = os.environ.get('CHROME_EXECUTABLE', 'google-chrome')
remote_debugging_port = os.environ.get('REMOTE_DEBUGGING_PORT', '9222')
chrome_process = None
ws_url = f"ws://localhost:{remote_debugging_port}"
session = None
try:
print(f"Launching {chrome_executable} with remote debugging on port {remote_debugging_port}...")
# Note: stderr/stdout are redirected to PIPE to avoid polluting the console
chrome_process = subprocess.Popen(
[chrome_executable, '--headless=new', f'--remote-debugging-port={remote_debugging_port}'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
time.sleep(3) # Give Chrome a moment to start and open the debugging port
# Connect to the running Chrome instance
print(f"Connecting to Chrome at {ws_url}...")
session = cdp.browser.connect(ws_url)
print("Successfully connected to Chrome.")
# Enable the Page domain to receive events and navigate
cdp.page.enable(session)
# Navigate to a URL
target_url = "https://www.example.com"
print(f"Navigating to {target_url}...")
cdp.page.navigate(session, url=target_url)
# Wait for the page to finish loading (load event)
cdp.page.wait_for_load_event(session)
print(f"Successfully navigated to {target_url}")
# Execute a JavaScript expression to get the page title
title_response = cdp.runtime.evaluate(session, expression="document.title")
if title_response and title_response.result:
print(f"Page title: {title_response.result.value}")
# Example: Get all cookies
cookies_response = cdp.storage.get_cookies(session)
if cookies_response and cookies_response.cookies:
print(f"Found {len(cookies_response.cookies)} cookies.")
# for cookie in cookies_response.cookies:
# print(f" - {cookie.name}: {cookie.value}")
except Exception as e:
print(f"An error occurred: {e}")
# Print stderr if Chrome process is available and has output
if chrome_process:
try:
_, stderr_output = chrome_process.communicate(timeout=1)
if stderr_output:
print("Chrome stderr:", stderr_output)
except subprocess.TimeoutExpired:
chrome_process.kill()
print("Chrome stderr: Process timed out during communicate, killed.")
finally:
# Always close the CDP session and terminate the Chrome process
if session:
print("Closing CDP session...")
cdp.browser.close(session)
if chrome_process and chrome_process.poll() is None:
print("Terminating Chrome process...")
chrome_process.terminate()
try:
chrome_process.wait(timeout=5)
except subprocess.TimeoutExpired:
chrome_process.kill()
print("Chrome process did not terminate gracefully, killed.")
print("Quickstart finished.")