PhantomJS 是异步的。通过致电page.open()
多次使用循环,实际上会加速回调的执行。您正在使用新请求完成之前覆盖当前请求,然后再次覆盖该新请求。您需要一个接一个地执行它们,例如如下所示:
page.open(url, function () {
waitFor(function() {
// something
}, function() {
page.open(url, function () {
waitFor(function() {
// something
}, function() {
// and so on
});
});
});
});
但这很乏味。有一些实用程序可以帮助您编写更好的代码,例如async.js https://github.com/caolan/async。您可以通过npm将其安装在phantomjs脚本的目录中。
var async = require("async"); // install async through npm
var tests = urls.map(function(url){
return function(callback){
page.open(url, function () {
waitFor(function() {
// something
}, function() {
callback();
});
});
};
});
async.series(tests, function finish(){
fs.write('test.txt', output);
phantom.exit();
});
如果您不需要任何依赖项,那么定义您自己的递归函数也很容易(来自here https://stackoverflow.com/a/31188699):
var urls = [/*....*/];
function handle_page(url){
page.open(url, function(){
waitFor(function() {
// something
}, function() {
next_page();
});
});
}
function next_page(){
var url = urls.shift();
if(!urls){
phantom.exit(0);
}
handle_page(url);
}
next_page();