You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CDP无法在Chrome中启用DOM的问题求助

解决CDP中DOM.enable成功后仍提示DOM agent未启用的问题

问题背景

通过DevTools Protocol(CDP)连接启用--remote-debugging-port=0的Chrome实例,使用以下Python WebSocket代码通信:

async def send(ws, command):
    await ws.send(json.dumps(command))
    async for message in ws:
        response = json.loads(message)
        return response


async def send_msg(url, msg):
    print(f"sending to url {url} with message {msg}")
    async with websockets.connect(url) as ws:
        response = await send(ws, msg)
        return response

已成功执行Browser.close、Page.navigate等命令,但调用DOM.performSearch等DOM相关命令时,收到错误:

{'id': 2, 'error': {'code': -32000, 'message': 'DOM agent is not enabled'}}

手动发送DOM.enable命令(响应显示成功)后,问题依旧存在。

解决思路

  • 复用同一个WebSocket连接
    当前代码每次调用send_msg都会新建WebSocket连接,而CDP的agent状态是绑定在连接上的。在一个连接里启用DOM agent后,换另一个连接执行DOM命令时,新连接的DOM agent仍处于未启用状态。
    修改代码保持连接持续打开,所有命令通过同一个连接发送:

    class CDPClient:
        def __init__(self, url):
            self.url = url
            self.ws = None
    
        async def connect(self):
            self.ws = await websockets.connect(self.url)
    
        async def send(self, command):
            await self.ws.send(json.dumps(command))
            async for message in self.ws:
                response = json.loads(message)
                if 'id' in response and response['id'] == command['id']:
                    return response
    
        async def close(self):
            await self.ws.close()
    
    # 使用示例
    async def main():
        client = CDPClient("ws://your-chrome-debug-url")
        await client.connect()
        # 先启用DOM agent
        await client.send({'id': 0, 'method': 'DOM.enable', 'params': {}})
        # 再执行DOM命令
        result = await client.send({'id': 1, 'method': 'DOM.performSearch', 'params': {'query': 'body'}})
        print(result)
        await client.close()
    
  • 确保命令执行顺序
    必须等待DOM.enable的响应返回后,再发送DOM相关命令。复用连接的代码通过await保证了命令的顺序执行,避免异步消息处理导致的时序问题。

  • 同时启用Page agent
    部分DOM操作依赖Page agent的激活状态,尝试先启用Page再启用DOM:

    {'id': 0, 'method': 'Page.enable', 'params': {}}
    {'id': 1, 'method': 'DOM.enable', 'params': {}}
    
  • 确认连接的是标签页级端点
    DOM agent属于标签页(Page)级别,若连接的是Chrome的Browser级WebSocket端点,会导致DOM命令失效。可通过访问http://localhost:<port>/json获取对应标签页的WebSocket地址,确保连接目标正确。

内容的提问来源于stack exchange,提问作者Ash Olorenshaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 19:37:11