Skip to content

Instantly share code, notes, and snippets.

@gh640
Created June 8, 2016 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gh640/44bc86959d4992e750f17da0d8cc7395 to your computer and use it in GitHub Desktop.
Save gh640/44bc86959d4992e750f17da0d8cc7395 to your computer and use it in GitHub Desktop.
CasperJS でログインが必要なページをまとめてキャプチャするスクリプト
// 指定されたログインサイトのページのキャプチャを取得する
//
// 利用方法:
// 1. config の中身を適宜編集する。基本的にはサイトルートとパスのみ変えれば OK です。
// 2. 実行する。次のコマンドで実行します: `casperjs __FILE__`
//
// 前提条件:
// - CasperJS と PhantomJS がインストールされている
//
// 注意点:
// - CasperJS は既存のキャプチャファイルが存在する場合も警告なく上書きします。
// - 各キャプチャのファイル名はページのパスをもとに決めています。
// ルールは単純に `/` と `.` を `-` に置き換えるというシンプルなものなので
// 正しく管理して暴走しないようにご注意ください。例は次のとおり。
// - node/36 -> node-36.png
// - admin/commerce/order -> admin-commerce.order.png
// - SSL 証明書のないサイトでテストする場合はコマンド実行時に追加要: `--ignore-ssl-errors=true`
//
// TODO:
// - config を別ファイルの YAML 化
// see: https://www.npmjs.com/package/yamljs
// 設定
var config = {
// キャプチャ出力先ディレクトリ
resultDir: 'result',
// ログインを必要とするかどうか
isLoginRequired: true,
// [変更要] サイトルート(末尾のスラッシュはつけないこと)
siteRoot: 'http://example.com',
// [変更要] ログインページのパス
loginPath: '/user',
// [変更要] ログインフォームの ID
loginFormId: '#user-login',
// [変更要] ログインのパラメータ
loginParams: {
name: 'YOUR_USER_NAME',
pass: 'YOUR_PASSWORD'
},
// 画面サイズ
viewportSize: {
width: 1200,
height: 1100
},
// キャプチャ対象ページのパス
paths: [
'/',
'/user',
]
};
// モジュールの読み込み
var fs = require('fs');
var casper = require('casper').create({
// ログを標準出力に戻す
// @see http://docs.casperjs.org/en/latest/modules/casper.html#casper-options
verbose: true,
// ログレベルを設定
// debug info warning error
logLevel: 'info',
// 画面サイズを設定
viewportSize: config.viewportSize
});
// メイン関数の実行
main();
// メイン関数
function main() {
// 事前処理
showProcessSummary();
makeResultDir();
// 本処理
casper.start();
casperLogin(casper);
casperCaptureAll(casper);
casper.run();
}
// 関数
/**
* config で指定された対象サイトにログインする
*
* config 内のログイン関連のパラメータを使用してログインする。
* ただし config.isLoginRequired が false の場合はログインしない。
*
* @param casper CasperJS のインスタンス。
*/
function casperLogin(casper) {
// ログインが必要と config で指定されている場合のみログインする,
if (config.isLoginRequired) {
// ログインする
var loginUrl = config.siteRoot + config.loginPath;
casper.start(loginUrl);
casper.then(function () {
this.fill(config.loginFormId, config.loginParams, true);
});
// ログインが完了したらメッセージを表示
casper.then(function () {
console.log('Logged in through: ' + loginUrl);
});
} else {
casper.start(config.siteRoot);
console.log('No log in executed.');
}
}
/**
* config で指定されたすべてのページのキャプチャを作成する
*
* @param casper CasperJS のインスタンス。
*/
function casperCaptureAll(casper) {
for (var i = 0; i < config.paths.length; i++) {
var url = config.siteRoot + config.paths[i];
casperCaptureOne(casper, url);
}
}
/**
* ページを 1 件キャプチャする
*
* @param casper CasperJS のインスタンス。
* @param url 対象ページの URL 。
*/
function casperCaptureOne(casper, url) {
casper.thenOpen(url, function () {
var fileCapture = toSafeFileName(url);
var fileCapturePath = config.resultDir + '/' + fileCapture;
casper.capture(fileCapturePath);
console.log('Captured: ' + url + ' -> ' + fileCapturePath);
});
}
/**
* URL を元に安全なファイル名を生成する
*
* @param url 対象 URL
*
* @return 渡された URL を元に生成したキャプチャファイル名
* 例: http://localhost/abc/def -> abc-def.png
*/
function toSafeFileName(url) {
// TODO
var indexSlash, path, fileNameSafe;
indexSlash = url.indexOf('/', 8);
if (indexSlash != -1) {
path = url.slice(indexSlash + 1);
} else {
console.log('Path cannot be taken from: ' + url);
process.exit();
}
// フロントページのファイル名が空になるので特別な名前を付ける
if (path === '') {
path = '__front';
}
// '/' や '.' をすべて - に置換する
fileNameSafe = path.replace(/[\/\.]/g, '-') + '.png';
return fileNameSafe;
}
/**
* 結果出力先ディレクトリを作成する
*/
function makeResultDir() {
var path = config.resultDir;
// @see http://phantomjs.org/api/fs/method/make-directory.html
if (fs.isDirectory(path)) {
console.log('Output directory "' + path + '" already exists.');
} else if (fs.makeDirectory(path)) {
console.log('Output directory "' + path + '" was created.');
} else {
console.log('Output directory "' + path + '" is NOT created.');
process.exit();
}
}
/**
* キャプチャプロセスのサマリー情報を表示する
*/
function showProcessSummary() {
console.log('Target site: ' + config.siteRoot);
console.log('Target page count: ' + config.paths.length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment