puppeteer 安装时跳过 chrome 安装的方法
puppeteer 安装时跳过下载 chrome
在项目目录里安装 puppeteer 时,都会下载 Chromium。这个慢不说,也会造成重复下载、耗时过长等问题。那么可以这么来做跳过 Chromium 的下载:
1 | npm install puppeteer --ignore-scripts |
然后在脚本中通过配置项 executablePath
,指定 Chromium 所在的位置(也可以指定为本地 Chrome 浏览器安装的地址)。示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 | const puppeteer = require( 'puppeteer' ); puppeteer.launch({ headless: false , // executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', executablePath: 'C:\\Program Files\\nodejs\\node_modules\\puppeteer\\.local-chromium\\win64-508693\\chrome-win32\\chrome.exe' }).then( async browser => { const page = await browser.newPage(); await page.screenshot({path: 'lzwme.png' }); browser.close(); }). catch (err => { console.log(err); }); |
提示:
当前淘宝仓库已经有该镜像,可以通过设置环境变量方式从该镜像地址进行下载安装。命令示例:
1 2 3 | # window set PUPPETEER_DOWNLOAD_HOST=https: //npm .taobao.org /mirrors npm install puppeteer |
手动下载 chrome
有的同学可能会问,在墙里下载不到开发版的 chrome 怎么办。翻看仓库源码可以得知,下载地址是这样的:
1 2 3 4 5 6 | const downloadURLs = { }; |
选择对应的平台,将 %d
替换成具体的编号,然后使用迅雷这种 P2P 下载即可。这个编号可以从 puppeteer/package.json
中的 puppeteer.chromium_revision
字段获得。
另外,你也可以从淘宝镜像仓库进行下载,地址如下:
https://npm.taobao.org/mirrors/chromium-browser-snapshots/
相关参考:
https://github.com/GoogleChrome/puppeteer/issues/244
https://github.com/GoogleChrome/puppeteer/issues/288
关于 puppeteer
在以前,当需要进行无界面的浏览器自动访问网站执行动作时,大都会选择 phantomjs 或 SlimerJS。
在 https://lzw.me/a/slimerjs-phantomjs-casperjs.html 这篇文章中我们对 phantomjs 进行了简单的使用介绍。
puppeteer 则是 chrome 官方团队出品的同类工具。当 puppeteer 出来后,phantomjs 即宣布不再继续开发维护。puppeteer 的使用很简单,功能更丰富,可以通过脚本实现各种自动化功能需求。
本文不对 puppeteer 具体使用作详细介绍。关于 puppeteer 的使用示例可参考这几篇文章:
https://github.com/laispace/puppeteer-explore
https://github.com/zhentaoo/puppeteer-deep
https://cloud.tencent.com/community/article/529168
https://github.com/GoogleChrome/puppeteer
安装puppeteer时如果无法下载Chromium,可以使用puppeteer-cn代替的。这个包先检查你本地chrome是否大于59,再决定是否安装Chromium,并且使用国内源安装,速度很快且保证成功。
请问我在mac下 executablePath:’/Applications/Google Chrome.app/Contents/MacOS/Google\ Chrome’ 设置成这样。
结果报错 UnhandledPromiseRejectionWarning: Error: Failed to launch chrome! spawn /Applications/Google Chrome.app/Contents/MacOS/Google\ Chrome ENOENT
是这个路径的问题么?
是的,ENOENT一般是没找到文件或路径
你的路径应该是有问题的
好文章,需要懂得欣赏的人,博主辛苦了