Webページをスクレイピングしてる時、HTMLじゃなくてJavaScriptの変数をのぞきたい事が稀によくある。

インストール

brew install phantomjs


document.titleを取得


page_title.js
var url = phantom.args[0] || 'http://shokai.org';

page = new WebPage();
page.open(url, function(stat){
if(!stat){
phantom.exit();
}
else{
var title = page.evaluate(function(){
return document.title;
});
console.log(title);
phantom.exit();
}
});
実行
phantomjs page_title.js http://google.com


titleのような1つの文字列だけでなく、オブジェクトもそのまま取り出せる。


ちょっと待ってから取得

onLoad後にajaxで何かデータ取得してる系のサイトで使う。
setTimeoutでちょっと待てばいい。
var url = phantom.args[0] || 'http://shokai.org';

page = new WebPage();
page.open(url, function(stat){
if(!stat){
phantom.exit();
}
else{
setTimeout(function(){
var title = page.evaluate(function(){
return document.title;
});
console.log(title);
phantom.exit();
}, 3000); // ちょっと待ってから取得
}
});


Basic認証


openする前にsettingsに書いておけばok
page = new WebPage();
page.settings.userName = "shokai";
page.settings.password = "zanmai";