Puppeteer 是 Google 官方维护的 Node.js 库,通过 DevTools Protocol (CDP) 控制基于 Chromium 内核的浏览器(Chrome、Edge 等),可用于:
网页自动化:表单提交、UI 测试、键盘输入等
爬虫:抓取 SPA(单页应用)渲染后的内容
生成页面截图和 PDF
性能分析与监控
官方文档:https://pptr.dev/
API 参考:https://pptr.dev/api
DevTools Protocol:https://chromedevtools.github.io/devtools-protocol/
本工具是通过 puppeteer.connect 连接到已开启调试模式的本地浏览器,在浏览器中执行 Puppeteer 代码。
启用浏览器调试模式
注意
启动前必须完全退出浏览器(包括后台进程),否则新命令只会在已有实例中打开新标签页,调试参数会被忽略。可先执行 taskkill /F /IM chrome.exe(Edge 将进程名换成 msedge.exe)。
返回格式 ws://localhost:9222/devtools/browser/<id> 的调试连接地址,填入上面的 webSocketDebuggerUrl 输入框,点击“链接”按钮即可连接浏览器。
Windows
powershell
Start-Process chrome -ArgumentList '--remote-debugging-port=9222', "--user-data-dir=$PWD\chrome-user-data", '--remote-allow-origins=*'
(curl http://localhost:9222/json/version | ConvertFrom-Json).webSocketDebuggerUrlpowershell
Start-Process msedge -ArgumentList '--remote-debugging-port=9222', "--user-data-dir=$PWD\edge-user-data", '--remote-allow-origins=*'
(curl http://localhost:9222/json/version | ConvertFrom-Json).webSocketDebuggerUrlMac
sh
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --user-data-dir="$PWD/chrome-user-data" --remote-allow-origins="*"
curl -s http://localhost:9222/json/version | grep -o '"webSocketDebuggerUrl": *"[^"]*"'sh
/Applications/Microsoft\ Edge.app/Contents/MacOS/Microsoft\ Edge --remote-debugging-port=9222 --user-data-dir="$PWD/edge-user-data" --remote-allow-origins="*"
curl -s http://localhost:9222/json/version | grep -o '"webSocketDebuggerUrl": *"[^"]*"'Linux
sh
google-chrome --remote-debugging-port=9222 --user-data-dir="$PWD/chrome-user-data" --remote-allow-origins="*"
curl -s http://localhost:9222/json/version | grep -o '"webSocketDebuggerUrl": *"[^"]*"'sh
microsoft-edge --remote-debugging-port=9222 --user-data-dir="$PWD/edge-user-data" --remote-allow-origins="*"
curl -s http://localhost:9222/json/version | grep -o '"webSocketDebuggerUrl": *"[^"]*"'