ヘッドレスブラウザ(phantomJS, slimerJS )で動的なWEBサイトをスクレイピングする

ヘッドレスブラウザとは「画面がないWEBブラウザ」の事です。
最近では Headless Chrome が人気です。 参考 : https://goo.gl/NQsFS2
が、npm だけでインストールできる phantomJS を紹介します。

● phantomJS

WebKit(Safari) ベースのヘッドレス(画面なし)ブラウザ

・phantomJSのインストール方法(npm のみでインストールする方法)

npm install phantomjs

以下のパスを手動で追加します

./node_modules/phantomjs/bin/phantomjs

・phantomJSのインストール方法(Mac の brew を使う方法)

brew install phantomjs

・phantomJSのインストール方法(CentOS の yum を使う方法)

yum -y install freetype
yum -y install fontconfig
npm install -g phantomjs

● slimerJS

Gecko(firefox) ベースのヘッドレス(画面なし)ブラウザ

・slimerJSのインストール方法(Mac)

brew install slimerjs

・slimerJSのインストール方法(CentOS7)

npm install -g slimerjs

● casperJS

ヘッドレスブラウザを簡単に扱うライブラリ(JavaScript)です。 このcasperJSから「phantomJS」または「slimerJS」を操作します。

・casperJSのインストール方法(Mac)

brew install casperjs

・casperJSのインストール方法(CentOS7)

yum -y install freetype
yum -y install fontconfig
npm install -g casperjs

● casperJSからブラウザを操作してxpathで要素を取得し、画面のスクリーンショットを撮る

test.js で下記コードを保存

var AnchorArrays = [];
var casper = require('casper').create();
casper.start('http://flatsystems.net/kakunin.php', function() {
});
casper.then(function() {
	casper.wait(3000, function() {
	    // xpath要素の取得
	    var xpath = "//*[@id='my_id']";
	    var element = this.evaluate(function(path){
	                return __utils__.getElementByXPath(path).innerHTML;
	    },xpath);
	    console.log( element );

	//png
    	this.capture('kakunin.png');
    	console.log( 'キャプチャを作成しました。' );
	});
});
casper.run();

● casperJSからphantomJSで起動する

casperjs  test.js

● casperJSからslimerJSで起動する

casperjs  --engine=slimerjs test.js

slimerJSで起動するときは --engine=slimerjs を追加します。

● casperJSコードを実際のブラウザソースから生成する Chrome拡張機能

・Resurrectio

https://chrome.google.com/webstore/detail/resurrectio/kicncbplfjgjlliddogifpohdhkbjogm

関連エントリー

No.1067
01/29 13:40

edit

スクレイピング
xpath
slimerjs
phantomjs