CasperJSをCentOS 5/6にインストール
概要
ヘッドレスブラウザPhantomJSを使ってJavascriptでテスト/スクレイピングができるCasperJSをCentOS 5/6にインストールします。Node.jsは不要です。
インストール
rootで以下の作業を行います。
yum -y install fontconfig freetype libstdc++
cd
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.8-linux-x86_64.tar.bz2 -O phantomjs-1.9.8-linux-x86_64.tar.bz2
wget https://github.com/n1k0/casperjs/tarball/1.0.3 -O casperjs-1.0.3.tar.gz
cd /opt
tar jxvf ~/phantomjs-1.9.8-linux-x86_64.tar.bz2
mv phantomjs-1.9.8-linux-x86_64 phantomjs-1.9.8
tar zxvf ~/casperjs-1.0.3.tar.gz
mv n1k0-casperjs-76fc831 casperjs-1.0.3
cat << EOT >/etc/profile.d/casperjs.sh
export PATH=/opt/casperjs-1.0.3/bin:/opt/phantomjs-1.9.8/bin:\${PATH}
EOT
CentOS5のみ追加で以下の作業を行います。
yum install python26
cat << EOT >>/etc/profile.d/casperjs.sh
alias casperjs='python26 /opt/casperjs-1.0.3/bin/casperjs'
EOT
(オプション)スクリーンキャプチャで日本語を表示するにはフォントのインストールと設定を行います。rootで以下をインストールします。
yum -y install ipa-gothic-fonts ipa-mincho-fonts ipa-pgothic-fonts ipa-pmincho-fonts
ユーザ毎に~/fonts.confを以下の内容で作成します。
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<alias>
<family>serif</family>
<prefer>
<family>IPAP Mincho</family>
</prefer>
</alias>
<alias>
<family>sans serif</family>
<prefer>
<family>IPAP Gothic</family>
</prefer>
</alias>
<alias>
<family>sans-serif</family>
<prefer>
<family>IPAP Gothic</family>
</prefer>
</alias>
<alias>
<family>monospace</family>
<prefer>
<family>IPA Gothic</family>
</prefer>
</alias>
</fontconfig>
ユーザ毎にフォントキャッシュをクリアします。
fc-cache -fv
サンプル
サンプル1
以下の内容でsample.jsを作成します。
var casper = require('casper').create();
casper.start('http://fusic.co.jp/', function() {
this.echo(this.getTitle());
});
casper.run();
以下のコマンドで実行します。
casperjs sample.js
サンプル2(DOMの取得)
以下の内容でsample2.jsを作成します。
var casper = require('casper').create();
casper.start('http://fusic.co.jp/', function() {
var text = this.evaluate(function() {
return __utils__.findOne('meta[name="keywords"]').content;
});
this.echo(text);
});
casper.run();
以下のコマンドで実行します。
casperjs sample2.js
サンプル3(スクリーンキャプチャ)
フォントのインストールと設定を行ってから、以下の内容でsample3.jsを作成します。
var casper = require('casper').create({
viewportSize: {
width: 1024,
height: 768
}
});
casper.start('http://fusic.co.jp/', function() {
this.capture('fusic.png');
});
casper.run();
CentOS6は以下のコマンドで実行します。
env LANG=C casperjs sample3.js
CentOS5は以下のコマンドで実行します。
env LANG=C python26 /opt/casperjs-1.0.3/bin/casperjs sample3.js
参考にした情報
公式ドキュメントにCoffeeScript版やテストのことが書いてあります。また、jQueryを使うこともできるようです。
その他に参考にした記事です。
- casperJSでwebスクレイピング | THE SPORTS BUSINESS
- お手軽!CasperJSとJenkinsでサイトの自動テスト - Catcher in the tech