Javascript PhantomJS-onLoadFinished无缘无故调用了两次
这是我的密码:Javascript PhantomJS-onLoadFinished无缘无故调用了两次,javascript,phantomjs,Javascript,Phantomjs,这是我的密码: var system = require('system'); var page = require('webpage').create(); var server = require('webserver').create(); var system = require('system'); var someUrl = "http://sportfun.bg"; var port = 3000; //Screen resolution page.viewportSize
var system = require('system');
var page = require('webpage').create();
var server = require('webserver').create();
var system = require('system');
var someUrl = "http://sportfun.bg";
var port = 3000;
//Screen resolution
page.viewportSize = {
width: 1920,
height: 1080
};
//User agent
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36';
page.onConsoleMessage = function(msg) {
system.stderr.writeLine('Console: ' + msg);
};
var service = server.listen(port, function (request, response) {
//console.log('Request received at ' + new Date());
//console.log("Request" + JSON.stringify(request.post));
var POST = request.post;
//console.log("Bank:" + POST.bank);
// TODO: parse `request` and determine where to go
var step = 0;
page.open(someUrl, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log("Here0");
page.onLoadFinished = function(status) {
if(status === "success"){
console.log("Here 1");
response.statusCode = 200;
response.headers = {
'Cache': 'no-cache',
'Content-Type': 'text/plain;charset=utf-8'
};
// TODO: do something on the page and generate `result`
response.write("We good");
//console.log(page.content);
response.close();
}
};
}
});
});
console.log("Server started!");
我使用的是PhantomJS2.1.1
当我启动服务器并在控制台中向其发送post请求时,我看到一件奇怪的事情:
Server started!
Here0
Here 1
Here 1
为什么我在这里看到两次1
,而实际上页面应该加载一次?
有什么原因吗?我如何修复它?如果有多个通过iframe嵌入的小部件,比如Facebook小部件或谷歌地图,则会多次回调onLoadFinished。您可以通过将对这些站点的调用列入黑名单来消除它们:
block_urls = ['gstatic.com', 'google-analytics.com', 'tawk.to', 'perdeta.net', 'facebook.net', 'facebook.com'];
page.onResourceRequested = function(requestData, request){
for(url in block_urls) {
if(requestData.url.indexOf(block_urls[url]) !== -1) {
request.abort();
console.log(requestData.url + " aborted");
return;
}
}
}
如果您实施此解决方案,您将注意到“here1”不再打印。这是因为第一个onLoadFinished
实际上是在页面之前启动的。打开,但只有在调用page.open
之后才创建它
如果您想真正使用page.onLoadFinished,您应该在页面打开之前将其重新标记。如果我不想中止请求,该怎么办?有没有办法识别实际的页面。onLoadFinished?@LucasSteffen是的,你可以通过var URL=page.evaluate(function(){return document.location.href})
在onLoadFinished
中获取当前的URL,但它不起作用,在我的例子中,页面重定向到主页并被触发6次,每页3次,同样的地址,为什么不提出一个新的问题,这样我们就可以进行调查?当然,我需要URL来检查。