#Puppeteer

在以root用户运行Puppeteer程序时,遇到一些错误,这里记录下解决的过程。
首先提示一个X11错误,这是因为我在服务器上运行Chrome,而服务器没有安装桌面环境导致的。
安装以下依赖项即可,以Debian系统为例:

1
apt-get install gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget

接着就是报了一个sandbox错误,报错内容是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(node:4963) UnhandledPromiseRejectionWarning: Error: Failed to launch chrome!
[0428/104254.469304:ERROR:zygote_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.


TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md

at onClose (/root/monkey/node_modules/puppeteer/lib/Launcher.js:342:14)
at Interface.helper.addEventListener (/root/monkey/node_modules/puppeteer/lib/Launcher.js:331:50)
at emitNone (events.js:111:20)
at Interface.emit (events.js:208:7)
at Interface.close (readline.js:370:8)
at Socket.onend (readline.js:149:10)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
(node:4963) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:4963) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

不了解具体的含义,但是从sandbox来看,应该是和Chrome的安全沙箱有关,单纯的想解决这个问题,只需要在代码中加入--no-sandbox启动Chrome的参数即可。

Example:

1
2
3
4
5
6
7
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({args: ['--no-sandbox']});
const page = await browser.newPage();
await page.goto("https://www.baidu.com");
await browser.close();
})()

Tips:

但是这样做可能会造成一些风险,主要是Chrome的sandbox会多一些安全特性(我理解的),如果是将Node的代码作为生产环境运行在产品中,还是需要谨慎一些的,确保请求的站点安全可信(最好不信)。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×