can't run puppeteer in centos7 解决思路

2,011 阅读2分钟

什么是 Puppeteer?

Puppeteer(中文翻译”木偶”) 是 Google Chrome 团队官方的无界面(Headless)Chrome 工具,它是一个 Node 库,提供了一个高级的 API 来控制 DevTools协议上的无头版 Chrome!

具体关于Puppeteer的更多安利介绍,可参考这篇文章: juejin.cn/post/684490…

如何安装

npm i --save puppeteer
或
yarn add puppeteer

安装其实很简单,它本身就是一个node包!

几行demo代码

const puppeteer = require('puppeteer');

(async() => {
  const browser = await puppeteer.launch();
  console.log(await browser.version());
  await browser.close();
})();

接下来才是本文的重点,报错了如何解决?

libXcomposite.so.1 => not found

这种错误往往是因为缺少必要的依赖,google一下,发现有人提过同样的问题:github.com/GoogleChrom…

解决办法:

1.查看有多少依赖没有安装

cd chrome目录
ldd chrome | grep not #列出还未安装的依赖

执行完上面命令后,我们会看到有如下依赖没有安装,以我的机器为例:

2.安装相应依赖

如何安装这些依赖呢?怎么知道对应的依赖是在哪个软件包里呢?这里就要安利一个非常棒的工具--yum-utils

Yum是linux上使用最广泛的包安装工具,相较于源码编译安装,它最大的好处就是能够自动帮我们处理依赖关系,通常只用执行 yum install -y xxx 即能安装某个软件,十分方便!

yum-utils 则是yum的扩展工具包,提供了一些非常好用的工具,repoquery就是其中之一!repoquery就是用来查询包的依赖关系,能通过依赖查询到对应的包!

# 安装 yum-utils
yum install -y yum-utils

# 通过依赖查询包
repoquery libXcomposite.so.1

# 安装包
yum install -y libXcomposit

按照上面的步骤挨个装好各个依赖,则依赖问题全部解决!

repoquery其实很强大,关于它更多的用法请参考:linux.die.net/man/1/repoq…

sandbox沙箱问题

解决完上面的依赖问题,我们再次执行会碰到新的问题:

(node:30559) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Failed to connect to chrome!
(node:30559) [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.

解决方法就是我们在 launch 的时候加上 sandbox相关参数:

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();
})();

Ok,最后终于执行成功!

最后

墙列推荐大家去了解下 repoquery !linux下安装包依赖缺失是比较常见的错误,借助于yum-utils的一些工具,可以让我们快速解决一些问题!