如何无需Debugger启用、暂停、恢复Chrome DevTools?WebSocket调用报错解决
问题背景
前置条件
- 运行Python编写的Selenium脚本
- 脚本启动后,尝试连接Chrome DevTools并控制脚本执行以进行调试
- 在Selenium脚本开始回放时,获取WebSocket URL并执行指定代码片段
Python连接Chrome DevTools的代码片段
def connect_devtools(ws_url): global ws ws = websocket.WebSocketApp(ws_url, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close) # Run WebSocket in a separate thread to keep it open wst = threading.Thread(target=ws.run_forever) wst.daemon = True wst.start() time.sleep(1) # Wait for the connection to be established def enable_debugger(): enable_debugger_command = { "id": 1, "method": "Debugger.enable", "params": {} } ws.send(json.dumps(enable_debugger_command)) def pause_debugger(): if ws: pause_command = { "id": 2, "method": "Debugger.pause", "params": {} } ws.send(json.dumps(pause_command)) else: print("WebSocket is not connected") def on_open(ws): print("WebSocket connection opened") def on_message(ws, message): print("Received message: ", message) if __name__ == "__main__": ws_url = "ws://127.0.0.1:35192/devtools/browser/9e552787-2329-4e7d-9cca-77a60e8d603c" # Replace with your actual WebSocket URL connect_devtools(ws_url) # Wait a bit before pausing to see the effect time.sleep(2) enable_debugger pause_debugger()
执行输出
WebSocket connection opened Received message: {"id":1,"error":{"code":-32601,"message":"'Debugger.enable' wasn't found"}} Received message: {"id":2,"error":{"code":-32601,"message":"'Debugger.pause' wasn't found"}}
问题
WebSocket连接已成功建立,但无法执行暂停操作。请问是否存在无需Debugger即可启用、暂停、恢复Chrome DevTools的方法?
解决方案
你遇到的核心问题是当前连接的是浏览器全局级别的DevTools WebSocket端点(/devtools/browser/...),而非具体页面的DevTools端点。浏览器全局端点不支持Debugger域的命令,只有页面级端点才能执行这类调试操作。
解决步骤
获取目标页面的DevTools端点
通过已连接的浏览器全局WebSocket发送Target.getTargets命令,获取所有页面的目标信息,筛选出类型为page的目标,提取它的webSocketDebuggerUrl:def get_page_target(): get_targets_cmd = { "id": 3, "method": "Target.getTargets", "params": {} } ws.send(json.dumps(get_targets_cmd))收到返回结果后,解析出目标页面的WebSocket URL。
连接页面级DevTools端点
使用拿到的页面级URL重新建立WebSocket连接,之后再发送Debugger.enable和Debugger.pause命令就能正常生效。
另外,你的代码里存在一个语法错误:enable_debugger只是函数名,没有加括号调用,需要改成enable_debugger()。
无需显式启用Debugger的替代方法
如果不想依赖Debugger域,可以通过Runtime.evaluate执行JavaScript代码触发页面暂停:
def pause_via_runtime(): pause_cmd = { "id": 4, "method": "Runtime.evaluate", "params": { "expression": "debugger;" } } ws.send(json.dumps(pause_cmd))
这个方法会直接触发浏览器的调试断点,实现页面暂停,不需要提前启用Debugger域,但本质还是利用浏览器的调试机制。
内容的提问来源于stack exchange,提问作者sridattas
相关产品推荐
相关产品推荐

