LoginSignup
5
4

More than 1 year has passed since last update.

Linuxでスクリーンショットを撮るならHeadless Chromeで決まり!

Last updated at Posted at 2018-07-22

はじめに

君の鯖は。では、ウェブサイトのスクリーンショットを撮影しています。
環境はPHP +α なんですが、これが結構むずいです。

PHP PhantomJSだったり、wkhtmltoimageだったりを使ってきましたが、どうしてもレイアウト崩れが発生します。

最近?インフラをVPSに移行したので、Headless Chromeを試したら感動しました。

Headless Chrome

直訳すると頭のないとか、首を切られたとか不穏な単語が並びますが、
すごく簡単にいうとGUIがない、コマンドから使えるGoogle Chromeです。

GUIがないだけで、JavaScriptやレタリングは完璧で、スクリーンショット撮影にはもってこいです。(本来は自動テスト用)

--print-to-pdfを使えばPDFを取得することもできます。

使用例
google-chrome\
 --headless\
 --screenshot\
 --window-size=1280,1000\
 https://qiita.com/

alt

インストール方法

こちらをを参考に

リポジトリを用意して

vi /etc/yum.repos.d/google.chrome.repo

[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub

yumからインストールします。

yum update
yum install google-chrome-stable

エイリアスはお好みで

alias chrome="google-chrome"

ちなみに、公式ブログではchrome-canaryをインストールするよう書かれていますが、Stableで問題ありません
https://developers.google.com/web/updates/2017/04/headless-chrome?hl=ja

使い方

公式ブログを参考に

エイリアスあり
chrome --headless --screenshot https://qiita.com/
エイリアスなし
google-chrome --headless --screenshot https://qiita.com/

でカレントディレクトリにスクリーンショット(screenshot.png)が出力されます。

下記のようなエラーがでる場合は

Fontconfig warning: "/etc/fonts/fonts.conf", line 146: blank doesn't take any effect anymore. please remove it from your fonts.conf

/etc/fonts/fonts.confを開いて、86行目<blank>と146行目</blank>を消します。

"Fontconfig warning: line 146: blank doesn't take any effect anymore. please remove it from your fonts.conf" というエラーがRictyを入れ直したときに出たのでその対処法 - Qiita

オプション

オプションとして起動オプションが使えます。

スクリーンショット関連だと、

ファイル名指定
google-chrome\
 --headless\
 --screenshot="/temp/top.png"\
 https://qiita.com/
サイズ指定
google-chrome\
 --headless\
 --screenshot\
 --window-size=1280,1080\
 https://qiita.com/
証明書エラーを許容
google-chrome\
 --headless\
 --screenshot\
 --ignore-certificate-errors
 https://qiita.com/
ユーザーエージェント指定
google-chrome\
 --headless\
 --screenshot\
  --user-agent="Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko"\
 https://qiita.com/
言語指定
google-chrome\
 --headless\
 --screenshot\
 --lang=ja\
 https://qiita.com/
JavaScript無効
google-chrome\
 --headless\
 --screenshot\
 --disable-javascript
 https://qiita.com/
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4