我用一个网页尝试了这个代码,当我们按下keydown时,它的内容会动态加载。 (比如facebook)
目标是获取所有净流量并将其打印到控制台。
var page = require('webpage').create(),
system = require('system'),
address;
if (system.args.length === 1) {
console.log('Usage: netlog.js <some URL>');
phantom.exit(1);
} else {
address = system.args[1];
page.onLoadFinished = function(req) {
console.log('requested: ' + JSON.stiringify(req, undefined, 4));
};
page.open(url, function () {
page.sendEvent('keypress', page.event.key.keydown);
});
page.onResourceRequested = function (req) {
console.log('requested: ' + JSON.stringify(req, undefined, 4));
};
page.onResourceReceived = function (res) {
console.log('received: ' + JSON.stringify(res, undefined, 4));
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
}
phantom.exit();
});
}
答案 0 :(得分:1)
首先,PhantomJS是异步的。您同时打开两个页面。当第二页page.open()
加载第一页时中止。这意味着您的page.sendEvent()
来电永远不会被执行。
如果您想查看事件是否正在执行某些操作,您需要让页面加载并在执行某些操作后稍等一下以查看是否有请求:
if (system.args.length === 1) {
console.log('Usage: netlog.js <some URL>');
phantom.exit(1);
} else {
address = system.args[1];
page.onResourceRequested = function (req) {
console.log('requested: ' + JSON.stringify(req, undefined, 4));
};
page.onResourceReceived = function (res) {
console.log('received: ' + JSON.stringify(res, undefined, 4));
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
phantom.exit(1);
}
page.sendEvent('keypress', page.event.key.keydown);
setTimeout(function(){
phantom.exit();
}, 1000);
});
}