是的,可以在预先存在的 Chrome 进程之上运行 puppeteer 实例。
为了实现这一点,首先需要使用remote-debugging-port选项启动Chrome进程,通常定义为:--remote-debugging-port=9222
这个Medium articule 非常详细地说明了如何实现这一点,但总结一下:
运行:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --no-first-run --no-default-browser-check --user-data-dir=$(mktemp -d -t 'chrome-remote_data_dir')
- 右键单击您的 Google Chrome 快捷方式图标 => 属性
- 在目标字段中,添加到最后 --remote-debugging-port=9222
应该类似于:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222
然后,您将能够导航到 http://localhost:9222/json/version(端口与您在上面定义的相同),并看到如下输出:
{
"Browser": "HeadlessChrome/87.0.4280.66",
"Protocol-Version": "1.3",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/87.0.4280.66 Safari/537.36",
"V8-Version": "8.7.220.25",
"WebKit-Version": "537.36 (@fd98a29dd59b36f71e4741332c9ad5bda42094bf)",
"webSocketDebuggerUrl": "ws://localhost:9222/devtools/browser/000aaaa-bb08-55af-a8e3-760dd9998fc7"
}
然后,您可以像这样使用 puppeteer connect() 方法(而不是 launch() 方法):
const browser = await puppeteer.connect({
browserWSEndpoint: "ws://localhost:9222/devtools/browser/000aaaa-bb08-55af-a8e3-760dd9998fc7",
});
// now, 'browser' is connected to your chrome window.
// get the opened pages
const openedPages = await browser.pages();
// filter out the one you want (telegram). not sure the best way to do it, please test it yourself
const telegramPage = openedPages.filter(page => page.url().includes("telegram"));