发送keydown事件在PhantomJS中不起作用
问题描述:
我试着用网页的代码,当我们按下keydown时,它的内容动态加载。 (如脸书)发送keydown事件在PhantomJS中不起作用
目标是获得所有净流量并将其打印到控制台。
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();
});
}
答
首先,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);
});
}
难道我的回答帮助?你有什么问题吗? –
是的,答案帮助我感谢 – Med