LoginSignup
6
4

More than 5 years have passed since last update.

[備忘録]CasperJSでWebページの指定画像を自動取得

Posted at

経緯

会社でリソースレポートを作る際、
個人的にはAPIが利用できるシステムでhtml化してさらっとやりたいんだけど、
他メンバーはOffice系の方が作りやすい!って状況がありました。

でも工数は以下のように変わらず、時間がとてもかかる。。。
① ブラウザでモニタリングシステムにログイン
② 該当ホストのリソースをグラフを確認
③ 一定の期間を指定して画像をダウンロード

それを改善するためにCasperJSを利用してみました。

動作環境

NodeJSで動作しますが、MacではHomebrewで簡単インストールができますので、
今回はHomebrewでインストールして試しています。

casperjsは、phantomjs最新だとstableでは未対応でしたので、
beta版をインストールしています。

% sw_vers
ProductName:    Mac OS X
ProductVersion: 10.9.5
BuildVersion:   13F34

% brew info phantomjs
phantomjs: stable 1.9.7 (bottled), HEAD
http://www.phantomjs.org/
/usr/local/Cellar/phantomjs/1.9.7_1 (104 files, 34M) *

% brew info casperjs 
casperjs: stable 1.0.4, devel 1.1-beta3, HEAD
http://www.casperjs.org/
/usr/local/Cellar/casperjs/1.1-beta3 (265 files, 1.9M) *

下記が今回作成したスクリプト例:

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

casper.start('http://yourdomain/index.php', function() {
       // ダウンロード開始をターミナルに出力(お好みで)
       this.echo("ダウンロード開始");
});
casper.waitForSelector("input[name='login_username']",
       // ログインユーザを指定
       function success() {
           this.sendKeys("input[name='login_username']", "user");
});
casper.waitForSelector("input[name='login_password']",
       // ユーザパスワードを指定
       function success() {
           this.sendKeys("input[name='login_password']", "password");
});
// ログイン処理を実施
casper.waitForSelector("form[name=login] input[type=submit][value='Login']",
       function success() {
           this.click("form[name=login] input[type=submit][value='Login']");
});
// 対象ページのグラフを名前(graph-name1.png)を指定してダウンロード
casper.thenOpen('http://yourdomain/', function(){
    var url = 'http://yourdomain/graph.php?id=1';
    this.download(url, 'graph-name1.png');
});
casper.thenOpen('http://yourdomain/', function(){
    var url = 'http://yourdomain/graph.php?id=2';
    this.download(url, 'graph-name2.png');
});
casper.then(function(){
    this.echo("ダウンロード終了");
});
// 実行
casper.run();

こんなコードを適当なファイル名で保存(今回はsample.jsとします)。

では、実行してみると・・・

%  casperjs sample.js
ダウンロード開始
ダウンロード終了

カレントフォルダにダウンロードしてきた画像が保存されました!

6
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
6
4