LoginSignup
2
1

More than 5 years have passed since last update.

PhantomJS で Screenshot を取る方法

Posted at

流れ

  • まずは PhantomJS をいれます
  • スクリプト書きます
  • phantomjs foo.js で実行します

Mac で動かします

Step1. まずは、brew で PhantomJS をインストール。

install_by_homebrew
$ brew install phantomjs
$ brew list phantomjs
# /usr/local/Cellar/phantomjs/2.1.1/bin/phantomjs
# /usr/local/Cellar/phantomjs/2.1.1/share/phantomjs/ (45 files)

Step2. スクリプトを書きます。

screenshot_phantomjs.js
var url = 'http://www.metro.tokyo.jp/'

// headlessブラウザを作る
var page = require('webpage').create();

page.viewportSize = { width: 1200, height: 600 };
page.clipRect = {
  top: 0,
  left: 0,
  width: 1200,
  height: 600
};

// 指定したURLを開く
page.open(url, function(status) {
  console.log("Status: " + status);
  if (status === "success") {
    page.render('./image_phantomjs.png');
  }
  phantom.exit();
});

Step3. コマンドを叩いて画像ができることを確認します。

$ phantomjs screenshot_phantomjs.js
Status: success

無事、同じディレクトリに、画像ができました。
スクリーンショット 2017-07-28 12.11.29.png

おまけ1. 切り取り位置の指定

clipRect を調整すれば、狙った箇所を切り取ることができます。

page.clipRect = {
  top: 200,
  left: 720,
  width: 500,
  height: 250
};

おまけ2. Docker コンテナにいれる場合

以下の sh スクリプトを Dockerfile で叩いていれています。

install_phantomjs.sh
apt-get update
apt-get install build-essential chrpath libssl-dev libxft-dev -y
apt-get install libfreetype6 libfreetype6-dev -y
apt-get install libfontconfig1 libfontconfig1-dev -y
cd ~
export PHANTOM_JS="phantomjs-2.1.1-linux-x86_64"
wget https://github.com/Medium/phantomjs/releases/download/v2.1.1/$PHANTOM_JS.tar.bz2
tar xvjf $PHANTOM_JS.tar.bz2
mv $PHANTOM_JS /usr/local/share
ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin
phantomjs --version

以上です。ありがとうございました。

Headless Chrome で同じようなことをしてみたいです。🚶🏼

2
1
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
2
1