centos安裝使用puppeteer和headless chrome

Google推出了無圖形界面的headless Chrome以後,能夠直接在遠程服務器上直接跑一些測試腳本或者爬蟲腳本了,猴開心!Google還附送了Puppeteer用於驅動沒頭的Chome。node

阿里的Macaca也順勢寫了Macaca-puppeteer,能夠在Macaca上直接寫通用的測試用例,在開發機上用圖形界面看效果,上服務器走生產,豈不是美滋滋。linux

然鵝,可達鴨眉頭一皺,發現事情並無那麼簡單。git

在阿里雲的Centos 7.3上,安裝puppeteer以後,會發現並不能啓動官方的example:github

const puppeteer = require('puppeteer');

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

  await browser.close();
})();

依賴安裝

仔細看錯誤棧,核心的錯誤是以下一段:chrome

...node_modules/puppeteer/.local-chromium/linux-496140/chrome-linux/chrome: error while loading shared libraries: libpangocairo-1.0.so.0: cannot open shared object file: No such file or directorydocker

TROUBLESHOOTING: https://github.com/GoogleChro...centos

原來puppet雖然幫你下了一個Chromium,但並無幫你把依賴都裝好。因而你要本身把那些so都裝好。promise

官方給的是Ubuntu版本的各個so包的apt-get安裝方式,centos版本竟然沒有放!因而遍歷了各個issue以後,終於發現仍是有人給出了centos的庫名,在一個看起來並不相關的issue裏瀏覽器

#依賴庫
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 -y

#字體
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

總算不用挨個去google了……bash

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.

要瘋掉了有沒有,這啥玩意啊!!!!關鍵是這時候另一個看起來是解決上面問題的issue,對這個錯誤進行了詳細的討論,然而直到今天(2017年9月27日)並無討論出什麼結果。

網上不少討論是說,直接調試那個Chrome。按照並不能解決問題的說法:直接去puppeteer的目錄找到.local-chrome裏面的Chromium執行文件,直接執行

./chrome -v --no-sandbox --disable-setuid-sandbox

(chrome:5333): Gtk-WARNING **: cannot open display:

發現加上了--no-sanbox實際上是能啓動的,可是提示沒有Gtk圖形界面,那乾脆加上--headless是否是就好了嘞?確實沒有報錯了。

回到puppeteer示例腳本,修改啓動瀏覽器的代碼,加上args:

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

啊哈,終於執行成功了。下載下來了example.com的截圖看了一眼,簡直淚流滿面。

回想一下,Puppet自己估計自帶了--headless,因此若是直接去命令行執行chrome,仍是要帶上--headless。

終於搞定這一切發現Macaca順便還提供了一個基於Ubuntu的Macaca-puppeteer的Docker,艾瑪這方便太多了,早知道不本身折騰了。

相關文章
相關標籤/搜索