让 AI 直接对话浏览器底层!这个开源库把 CDP 协议玩出了花

让 AI 控制浏览器底层协议,这个开源库把 CDP 玩出了花!

做 AI Agent 或者浏览器自动化的时候,你是不是也遇到过这些痛点:
– 用 Playwright/Puppeteer 感觉隔了一层,底层能力摸不到
– 想监听浏览器的网络请求、JS 执行、DOM 变化,API 复杂到想哭
– Chrome DevTools Protocol 文档读了好几遍,还是不知道怎么写 Python 代码

今天挖到的这个库——CDP Use,真的让我眼前一亮。

它是干嘛的?

CDP Use 是 browser-use 团队开源的 Python 库,专门把 Chrome DevTools Protocol(CDP)自动生成类型安全的 Python 绑定。简单说:你写 Python,底层直接调 Chrome 的原生协议,零损失。

官方这么说:

A type-safe Python client generator for the Chrome DevTools Protocol (CDP). Automatically generates Python bindings with full TypeScript-like type safety from the official CDP protocol specifications.

核心能力:
– 🔒 Type Safety:所有 CDP 命令、参数、返回值全部有类型提示,用 TypedDict 类定义
– 🎯 Event Registration:类型安全的事件处理器,IDE 全支持
– 🏗️ Auto-Generated:代码直接从 Chrome 官方协议规范自动生成
– 📦 Domain Separation:按 CDP 域(Page、Runtime、Network 等)清晰分模块
– 🔄 Always Up-to-Date:随时可以从最新协议规范重新生成

怎么用?

安装极简:

git clone https://github.com/browser-use/cdp-use && cd cdp-use
uv sync

然后一行命令生成最新的类型绑定:

python -m cdp_use.generator

连接浏览器并发送命令:

import asyncio
from cdp_use.client import CDPClient

async def main():
    async with CDPClient("ws://localhost:9222/devtools/browser/...") as cdp:
        targets = await cdp.send.Target.getTargets()
        print(f"Found {len(targets['targetInfos'])} targets")
        await cdp.send.Page.navigate({"url": "https://example.com"})

asyncio.run(main())

监听浏览器事件(超级适合 AI Agent 场景):

from cdp_use.cdp.page.events import FrameAttachedEvent
from cdp_use.cdp.runtime.events import ConsoleAPICalledEvent

def on_frame_attached(event: FrameAttachedEvent, session_id):
    print(f"Frame {event['frameId']} attached")

async def main():
    async with CDPClient("ws://localhost:9222/devtools/page/...") as client:
        client.register.Page.frameAttached(on_frame_attached)
        client.register.Runtime.consoleAPICalled(on_console)
        await client.send.Page.enable()
        await client.send.Page.navigate({"url": "https://example.com"})

支持的事件域:Page、Runtime、Network、DOM、CSS、Debugger、Performance、Security……共 50+ 个域,全部类型安全。

为什么值得关注?

browser-use 本身就是做 AI 浏览器自动化的大牛团队(107k ⭐ 的 browser-use 就是他们家的)。他们开源的这个 cdp-use 填补了一个很实在的空白:以前想用 CDP 得啃 Chrome 官方的协议文档 + 自己写 WebSocket 通信,现在一行命令自动生成 Python 绑定,还带完整的类型提示。

对于做 AI Agent 的开发者来说,这等于获得了一个直接操控浏览器底层的 Python 接口——可以用来做更精细的浏览器任务、获取更丰富的页面信息、或者训练数据采集。

目前 308 ⭐,最近还在活跃更新,commit 记录显示 3 天前刚修了一个依赖问题。


GitHub:https://github.com/browser-use/cdp-use
Stars:308
语言:Python


GitHub: https://github.com/browser-use/cdp-use

评论区

0 条评论

登录后可评论。

苏棠 2155 阅读