我把攔截代碼here和包裹在其中它注入我刮頁面PhantomJS腳本。請注意,在注入XHTTP攔截之前,必須加載頁面。 此外,必須告訴PhantomJS攔截並打印輸出到console.log的消息。
我使用維傑的接受的答案here
的[功能]技術對於一個更有趣的實時數據飼料試試下面用http://flightaware.com/live/而非maps.google.com,但要耐心等待,可能需要一分鐘五獲得更新。
這裏的
部分(除解析,對不起,未經測試等)
PhantomJS腳本:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
page.onConsoleMessage = function(msg) {
console.log(msg);
};
var steps = [
function() {
//Load Login Page
page.open("http://maps.google.com");
},
function() {
page.render('check.png'); // see what's happened.
page.evaluate(
function(x) {
//inject following code from https://gist.github.com/suprememoocow/2823600
// I've added console.log() calls along with onConsoleMessage above to see XHR responses.
(function(XHR) {
"use strict";
var stats = [];
var timeoutId = null;
var open = XHR.prototype.open;
var send = XHR.prototype.send;
XHR.prototype.open = function(method, url, async, user, pass) {
this._url = url;
open.call(this, method, url, async, user, pass);
};
XHR.prototype.send = function(data) {
var self = this;
var start;
var oldOnReadyStateChange;
var url = this._url;
function onReadyStateChange() {
if(self.readyState == 4 /* complete */) {
var time = new Date() - start;
stats.push({
url: url,
duration: time
});
console.log("Request:" + data);
console.log("Response:" + this.responseText);
if(!timeoutId) {
timeoutId = window.setTimeout(function() {
var xhr = new XHR();
xhr.noIntercept = true;
xhr.open("POST", "/clientAjaxStats", true);
xhr.setRequestHeader("Content-type","application/json");
xhr.send(JSON.stringify({ stats: stats }));
timeoutId = null;
stats = [];
}, 2000);
}
}
if(oldOnReadyStateChange) {
oldOnReadyStateChange();
}
}
if(!this.noIntercept) {
start = new Date();
if(this.addEventListener) {
this.addEventListener("readystatechange", onReadyStateChange, false);
} else {
oldOnReadyStateChange = this.onreadystatechange;
this.onreadystatechange = onReadyStateChange;
}
}
send.call(this, data);
}
})(XMLHttpRequest);
},""
);
},
function() {
// try something else here. Add more steps as necessary
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
// commented out to run until ctrl-c
//console.log("test complete!");
//phantom.exit();
}
}, 500);
已經嘗試過吧..沒解決問題 – Faisal 2014-11-13 03:29:15