LoginSignup
30

More than 5 years have passed since last update.

CasperJSでWEBサイトの画面キャプチャを取得してみた

Posted at

ブログにも書きましたが、こちらにも。


CasperJSは、JavaScriptで動かせるローカルの仮想ブラウザです(内部的にはWebKitを使ってるらしい)。WEBサイトのスクレイピングや、ブラウザ上のテストを自動化することができます。

また画面キャプチャもとれるようなので、今回はGoogleのトップページ画面をキャプチャするところまで試してみます。

環境構築

  • 環境は Mac OS X (Mavericks) とします。
  • インストールには npm を使います。

①まず事前にPhamtomJSが必要らしいのでインストール

# npm install -g phantomjs

②続いてCasperJSをインストール

# npm install -g casperjs

以上で環境の構築は完了です。試しにヘルプを表示してみます。

$ casperjs --help

CasperJS version 1.1.0-beta3 at /usr/local/lib/node_modules/casperjs, using phantomjs version 1.9.7
Usage: casperjs [options] script.[js|coffee] [script argument [script argument ...]]
       casperjs [options] test [test path [test path ...]]
       casperjs [options] selftest
       casperjs [options] __selfcommandtest

Options:

--verbose   Prints log messages to the console
--log-level Sets logging level
--help      Prints this help
--version   Prints out CasperJS version
--engine=name Use the given engine. Current supported engine: phantomjs and slimerjs

Read the docs http://docs.casperjs.org/

利用してみる

公式サイトに載っている例を参考に、まずはGoogoleのトップページからタイトルを取得しています。次のように sample.js を用意し、

sample.js
var casper = require('casper').create();

casper.start('http://www.google.com', function() {
    this.echo(this.getTitle());
});

casper.run();

これを実行してみます。

$ casperjs sample.js

Google

タイトルが取得できました^^

次に、Googleのトップページ画面をキャプチャしてみます。次のように sample2.js を用意し、

sample2.js
var casper = require('casper').create();

casper.start('http://www.google.com', function() {
    this.capture('hoge.png');
});

casper.run();

これを実行してみます。

$ casperjs sample2.js

カレントディレクトリに hoge.png が作成されたので開いてみます。

hoge.png

キャプチャできました^^

おわりに

内部的に WebKit が動いている?ようなので、コマンドの結果が返るまでちょっとかかります。これを使って色々な自動化が出来そうな感触がしたので、今後、有効活用していきたいと思います。

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
30