Skip to main content

Chrome DevTools Protocol Toolkit in Python

Project description

CDPKit: A Python Implementation of the CDP(Chrome DevTools Protocol)Toolkit

English | 中文

Overview

CDPKit is a toolkit for the Chrome DevTools Protocol (CDP). The protocol component of this project is built on pydantic, supporting friendly code completion and parameter type checking. It also provides a connection module that enables CDP interactions via the remote-debugging-port.

Key Features

  • Type Safety: Leverages pydantic to automatically implement type checking for command inputs and outputs.
  • Rich Type Hints: Provides type hints for command results, eliminating the need to consult documentation for return values.
  • Dynamic Code Generation: Generates protocol code based on the official CDP JSON schema, ensuring fast updates.
  • Async Performance: Offers an asynchronous CDPSessionManager that abstracts communication logic, allowing direct method calls.

Installation

1. Install by pip

pip install cdpkits

2. Install by uv

curl -LsSf https://astral.sh/uv/install.sh | sh  # macOS and Linux
# on Windows:
# powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
  • 2.2. Clone the repository:
git clone https://github.com/yie1d/cdpkit.git  
cd cdpkit
  • 2.3. Create a new virtual environment and activate it:
uv venv
source .venv/bin/activate  # On Unix/macOS
# Or on Windows:
# .venv\Scripts\activate
  • 2.4. Install dependencies:
uv sync

Basic Usage

Quick Start

import asyncio
from cdpkit.connection import CDPSessionManager
from cdpkit.protocol import Target


async def main():
    # Connect to the currently running browser (debug port 9222)
    session_manager = CDPSessionManager(ws_endpoint='localhost:9222')
    cdp_session = await session_manager.get_session()
    
    # Get information on all currently open targets.
    target_resp = await cdp_session.execute(Target.GetTargets())

    for target_info in target_resp.targetInfos:
        print(target_info.model_dump())



asyncio.run(main())

Use CDPSessionExecutor

import asyncio
from cdpkit.connection import CDPSessionManager, CDPSessionExecutor
from cdpkit.protocol import Target, Page


async def on_dialog_open(event_data: Page.JavascriptDialogOpening):
    """
    Callback function for the alert dialog

    Args:
        event_data (Page.JavascriptDialogOpening): 
            If the event_data parameter is provided, 
            it must be used as the parameter for receiving the event and must match the actual event type.

    Returns:

    """
    print(event_data.message)

async def main():
    session_manager = CDPSessionManager(ws_endpoint='localhost:9225')
    browser_session = await session_manager.get_session()


    # execute command
    target_resp = await browser_session.execute(Target.GetTargets(filter_=[{
        'type': 'page',
        'exclude': False
    }]))

    target_id = None
    for target_info in target_resp.targetInfos:
        if not target_info.url.startswith('devtools://') and not target_info.url.startswith('chrome-extension://'):
            target_id = target_info.targetId
            break

    if not target_id:
        raise Exception('No target found')

    # Retrieve the specified target session
    cdp_session = await session_manager.get_session(target_id=target_id)
    session_executor = CDPSessionExecutor(session=cdp_session, session_manager=session_manager)

    # execute by CDPSessionExecutor
    # Enable page events
    await session_executor.execute_method(Page.Enable())

    # Listen for events
    await session_executor.on(
        event=Page.JavascriptDialogOpening,
        callback=on_dialog_open
    )

    # You can manually run alert('test Page.JavascriptDialogOpening event') in the browser's console to see the listener in action.
    await asyncio.sleep(500)



asyncio.run(main())

More usage

You can refer to webauto — a browser-automation tool based on CDPKit (work in progress).

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cdpkits-1.2.17.tar.gz (195.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cdpkits-1.2.17-py3-none-any.whl (276.1 kB view details)

Uploaded Python 3

File details

Details for the file cdpkits-1.2.17.tar.gz.

File metadata

  • Download URL: cdpkits-1.2.17.tar.gz
  • Upload date:
  • Size: 195.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.6

File hashes

Hashes for cdpkits-1.2.17.tar.gz
Algorithm Hash digest
SHA256 c582766b65aa98ea3e3b7f124e00f23a6f487ce70c7f3f60c5aa6ec1404ec2d6
MD5 72fd7241a14367a1071706a2d3b64856
BLAKE2b-256 4d4d1017e42c81acd9c30d9ffd934bc18129ca83d85dbb2f45243391f8f3f5eb

See more details on using hashes here.

File details

Details for the file cdpkits-1.2.17-py3-none-any.whl.

File metadata

  • Download URL: cdpkits-1.2.17-py3-none-any.whl
  • Upload date:
  • Size: 276.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.6

File hashes

Hashes for cdpkits-1.2.17-py3-none-any.whl
Algorithm Hash digest
SHA256 a55785d402105fb6734ba2665c404aefea366da80e2c08b59fc3af3a3f9a6d9f
MD5 743ba8df3128a6660bcdc86df532f753
BLAKE2b-256 f208454f15db6e6ddf09f7efa51107bbf1ee58aa2c5daeebc70a53aea3c3d6c9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page