MyCDP: Autogenerated Chrome DevTools Protocol Client

1.3.7 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This example launches a headless Chrome instance, connects to it via MyCDP, navigates to 'example.com', retrieves its title, and lists its cookies. It demonstrates connecting to a browser, enabling a CDP domain, and executing basic page and runtime commands. Ensure you have a Chrome/Chromium executable in your system's PATH (e.g., 'google-chrome', 'chromium').

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.")

view raw JSON →