首先是大家知道的安装依赖库慢的问题
// yarn 配置淘宝镜像
yarn config set registry https://registry.npm.taobao.org -g
// 然后安装puppeteer
yarn add puppeteer
// 等待安装,可能需要尝试多次
运行时出现的错误
1、缺少依赖库
error while loading shared libraries: libXtst.so.6: cannot open shared object file: No such file or directory
这是因为系统缺少一些puppeteer需要的一些依赖库。
#依赖库
yum install pango.x86_64 libXcomposite.x86_64 libXcursor.x86_64 libXdamage.x86_64 libXext.x86_64 libXi.x86_64 libXtst.x86_64 cups-libs.x86_64 libXScrnSaver.x86_64 libXrandr.x86_64 GConf2.x86_64 alsa-lib.x86_64 atk.x86_64 gtk3.x86_64 nss.x86_64 -y
2、截图或导出pdf看到的是乱码
这是因为缺少字体库
#字体
yum install ipa-gothic-fonts xorg-x11-fonts-100dpi xorg-x11-fonts-75dpi xorg-x11-utils xorg-x11-fonts-cyrillic xorg-x11-fonts-Type1 xorg-x11-fonts-misc -y
3、这时候你再去执行脚本,发现还是跑不起来。但是报错终于变了。这个时候变成了一个莫名其妙的错误:
Error: Failed to launch chrome! [0530/204923.175379:ERROR:z_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See crbug.com/63818
解决办法
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'example.png'});
await browser.close();
})();