我是 Node.js 的新手。我正在使用zombie.js 从几个网站上抓取网页标题。下面是我的代码:
var Browser = require("zombie");
var util = require("util");
halt = require('delayed');
title = [];
url = [ 'http://www.apple.com', 'http://www.microsoft.com', 'http://www.dell.com' ];
function getTitles(url){
//console.log('Start scraping title');
var length = url.length;
console.log('Total Site to Scrape: '+length);
label = 1;
for(var i=0;i<length;i++){
browser = new Browser()
browser.runScripts = false
browser.setMaxListeners(0);
browser.visit(url[i], function(e, browser, status, errors) {
browser.wait(function(){
title[i] = browser.text('html > head > title');
console.log(label+': '+title[i]);
browser.close();
label++;
});
});
};
}
getTitles(url);
halt.delay(function () {
console.log('Array Length: '+title.length)
console.log('Array Content: '+title)
}, 10)
下面是代码的输出:
Total Site to Scrape: 3
1: Apple
2: Dell Official Site - The Power To Do More | Dell
3: Microsoft Home Page | Devices and Services
Array Length: 4
Array Content: ,,,Microsoft Home Page | Devices and Services
我不明白的部分:
- 为什么返回的数组长度是 4 而不是 3?只有三个网址
- 为什么数组内容只返回最后一个元素?另外两个缺失的元素在哪里?