记一次在ubuntu18上使用puppeteer的经过

通过远程的code-server使用puppeteer实现在nodejs上也能给网页截图, 但是运行官网上的示例报错.如下:

const puppeteer = require('puppeteer')

;(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('https://bilibili/')
  await page.screenshot({ path: 'example.png' })
  await browser.close()
})()

运行后提示error:

Error: Failed to launch the browser process!

/var/app/current/node_modules/puppeteer/.local-chromium/linux-848005./chrome-linux/chrome: error while loading shared libraries: libxkbcommon.so.0: cannot open shared object file: No such file or directory

TROUBLESHOOTING: https://github/puppeteer/puppeteer/blob/main/docs/troubleshooting.md

at onClose (/var/app/current/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:193:20)

at Interface.<anonymous> (/var/app/current/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:183:68)

at Interface.emit (events.js:323:22)

at Interface.close (readline.js:409:8)

at Socket.onend (readline.js:187:10)

at Socket.emit (events.js:323:22)

at endReadableNT (_stream_readable.js:1204:12)

at processTicksAndRejections (internal/process/task_queues.js:84:21)

于是在github上的puppeteer/issues查询, 网址:

https://github/puppeteer/puppeteer/issues/6922

实际上是系统缺少一些包, 而且puppeteer的文档中也写得很详细:在

https://github/puppeteer/puppeteer/blob/main/docs/troubleshooting.md#chrome-headless-doesnt-launch-on-unix

由于我的系统是ubuntu18, 所以需要安装他列举的所有依赖

sudo apt-get install ca-certificates fonts-liberation libappindicator3-1 libasound2 libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 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 lsb-release wget xdg-utils -y

之后运行时, 提示另外一个错误:

(node:5267) UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
[0308/163337.932654:ERROR:zygote_host_impl_linux(90)] Running as root without --no-sandbox is not supported. See https://crbug/638180.

在文档中有提到,

https://github/puppeteer/puppeteer/blob/main/docs/troubleshooting.md#setting-up-chrome-linux-sandbox

将代码改为:

const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] })

就可以正常运行, 但是官方并不推荐我们这么做就是了, 在截图没截到的下方有其他推荐的做法.

更多推荐

使用puppeteer 提示Error: Failed to launch the browser process解决办法