オーソドックスなやつかと。
PhantomJSのサンプルといえば!的な。javascript
var page = require('webpage').create(); page.open('http://example.com', function(){ // do something.. page.evaluate(function(){ // do something... }); phantom.exit(); });
ネットワークの監視とか。html
var page = require('webpage').create(); page.onResourceRequested = function (request) { console.log('Request ' + JSON.stringify(request, undefined, 4)); }; page.onResourceReceived = function (response) { console.log('Receive ' + JSON.stringify(response, undefined, 4)); }; page.open(url);
とにかくいろいろサンプルあるので、先に見るとイメージがつかめるかもです。java
參考:phantomjs/examples at master · ariya/phantomjs · GitHubgit
Evaluates the given function in the context of the web page. The execution is sandboxed, the web page has no access to the phantom object and it can't probe its own setting.github
それは困った。web
// NG! var url = 'http://example.com', idPw = { id: 'hoge', pw: 'piyo' }; page.open(url, function(){ page.evaluate(function(){ document.getElementById('login-name').value = idPw.id; // Undefined!! document.getElementById('pass-word').value = idPw.pw; // Undefined!! document.getElementById('myForm').submit(); }); });
これは困った・・。ide
// OK! var url = 'http://example.com', idPw = { id: 'hoge', pw: 'piyo' }; page.open(url, function(){ page.evaluate(function(idPw){ document.getElementById('login-name').value = idPw.id; document.getElementById('pass-word').value = idPw.pw; document.getElementById('myForm').submit(); }, idPw); // 渡せた! });
やり方は2通り。
推奨されてるのは最初のやつだそうな。ui
// var page … page.settings = { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25' }; // page.open(…
// var page … page.customHeaders = { User-Agent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25' }; // page.open(…
この方法で設定すると、最初の方法を上書きしてしまうそうです。lua
ログインした後のリダイレクト待ちとか、そもそも重いページとか、単純なコールバックで上手くいかない時とか。
ここに書かれてる內容で、やりたいことのほとんどはできるのではないでしょうか。
あとはflow.jsとか。
ページへは、
if(!phantom.injectJs('./utils/jsdeferred.js')){ console.log('This script requierd jsdefferred.js!'); phantom.exit(1); }
という具合で差し込めば使えます。
まぁ當たり前ですが・・。
コールバックの嵐になりがちなあたりや、CommonJSスタイルでのモジュール読み込みとか。