オーソドックスなやつかと。PhantomJSのサンプルといえば!的な。
var page = require('webpage').create(); page.open('http://example.com', function(){ // do something.. page.evaluate(function(){ // do something... }); phantom.exit(); });ネットワークの監視とか。
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);とにかくいろいろサンプルあるので、先に見るとイメージがつかめるかもです。
参考:phantomjs/examples at master · ariya/phantomjs · GitHub
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.
それは困った。
// 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(); }); });これは困った・・。
やり方は2通り。推奨されてるのは最初のやつだそうな。
この方法で設定すると、最初の方法を上書きしてしまうそうです。
参考:uu59のメモ | phantomjsでadplannerの表示を見る
ログインした後のリダイレクト待ちとか、そもそも重いページとか、単純なコールバックで上手くいかない時とか。ここに書かれてる内容で、やりたいことのほとんどはできるのではないでしょうか。
あとはflow.jsとか。
参考:uupaa/flow.js · GitHub
ページへは、
if(!phantom.injectJs('./utils/jsdeferred.js')){ console.log('This script requierd jsdefferred.js!'); phantom.exit(1); }という具合で差し込めば使えます。
まぁ当たり前ですが・・。コールバックの嵐になりがちなあたりや、CommonJSスタイルでのモジュール読み込みとか。
PhantomJSのAPIをいろいろ調べるとか、するより先に、コレ使ったほうが早いし楽です。おそらくスクレイピング絡みのほとんどのことは、難なく実現できちゃいます。
CasperJSのメモとか、作ったサンプルはまた個別の記事で載せようと思います。
from:http://lealog.hateblo.jp/entry/2013/05/18/002824转载于:https://www.cnblogs.com/c-x-a/p/5395169.html
相关资源:phantomjs 2.1.1 for windows