将 cUrl 与 Chrome 远程调试结合使用

Use cUrl with Chrome remote debugging

我正在尝试使用 cUrl 连接到 Chrome 远程调试,但是 Chrome return 的响应是“200 OK”,但没有数据。

我设置 chrome 使用:

chrome.exe --headless --remote-debugging-port=12345

我可以成功获取页面列表:

>curl -i "http://localhost:12345/json"

HTTP/1.1 200 OK
Content-Length:612
Content-Type:application/json; charset=UTF-8
[ {
   "description": "",
   "devtoolsFrontendUrl": "/devtools/inspector.html?ws=localhost:12345/devtools/page/19d24d3a-25b7-4ee8-a5cf-4f3d17778575",
  ...
   "webSocketDebuggerUrl": "ws://localhost:12345/devtools/page/19d24d3a-25b7-4ee8-a5cf-4f3d17778575"
} ]

但是,我只能从调试器 URL 获得空的成功响应:

>echo {"id":0,"method":"Page.navigate","params":{"url":"https://whosebug.com/"}}|curl -i "http://localhost:12345/devtools/page/19d24d3a-25b7-4ee8-a5cf-4f3d17778575" -H "Content-Type: application/json" -d -

HTTP/1.1 200 OK
Content-Length:0
Content-Type:text/plain

Page.navigate 这样的命令和错误的请求 return 200 OK 但什么也没执行。

我错过了什么???

你需要使用 websockets 来管理 chrome 这样的。引用 chromedevtools.github.io:

Your application can discover available pages by requesting: http://localhost:9222/json and getting a JSON object with information about inspectable pages along with the WebSocket addresses that you could use in order to start instrumenting them

这就是它的工作方式(至少在我的 Mac 上):

运行 Chrome

docker pull deepsweet/chromium-headless-remote:69
docker run -it --rm -p 9222:9222 deepsweet/chromium-headless-remote:69

正在获取 WebSocket 地址

curl -i "http://localhost:9222/json"
HTTP/1.1 200 OK
Content-Length:361
Content-Type:application/json; charset=UTF-8

[ {
   "description": "",
   "devtoolsFrontendUrl": "/devtools/inspector.html?ws=localhost:9222/devtools/page/DC33B65CA373BE2770F2A1031C3B4CBF",
   "id": "DC33B65CA373BE2770F2A1031C3B4CBF",
   "title": "about:blank",
   "type": "page",
   "url": "about:blank",
   "webSocketDebuggerUrl": "ws://localhost:9222/devtools/page/DC33B65CA373BE2770F2A1031C3B4CBF"
} ]

正在发送您的命令

echo '{ "id":2, "method":"Page.navigate", "params":{"url": "http://www.whosebug.com"} }' | websocat -t - ws://localhost:9222/devtools/page/DC33B65CA373BE2770F2A1031C3B4CBF

websocat is used in the example. You can also write a simple script to do it like here

确保页面已打开

curl -i "http://localhost:9222/json"
HTTP/1.1 200 OK
Content-Length:432
Content-Type:application/json; charset=UTF-8

[ {
   "description": "",
   "devtoolsFrontendUrl": "/devtools/inspector.html?ws=localhost:9222/devtools/page/DC33B65CA373BE2770F2A1031C3B4CBF",
   "id": "DC33B65CA373BE2770F2A1031C3B4CBF",
   "title": "Stack Overflow - Where Developers Learn, Share, & Build Careers",
   "type": "page",
   "url": "https://whosebug.com/",
   "webSocketDebuggerUrl": "ws://localhost:9222/devtools/page/DC33B65CA373BE2770F2A1031C3B4CBF"
} ]