我正在尝试使用Request和Cheerio构建一个简单的网络爬虫。
现在的目标是抓取目标页面(在本例中为http://bukk.it),从页面上的目标选择器中抓取文本,并将其推送到我可以在其他函数中使用的数组中。
我知道这request()
是异步执行的,但不知道如何在函数外看到抓取的数据。
例子.js
// dependencies
var request = require('request')
, cheerio = require('cheerio');
// variables
var url = 'http://bukk.it/'; // url to scrape
var bukkits = []; // hold our scraped data
request(url, function(err, resp, body){
if (err) {
return
}
$ = cheerio.load(body);
// for each of our targets (within the request body)...
$('td a').each(function(){
content = $(this).text();
// I would love to populate the bukkits array for use later...
bukkits.push(content);
})
console.log(bukkits.length); // everything is working inside request
});
console.log(bukkits.length); // nothing, because request is asynchronous?
// that's cool but... how do I actually get the data from the request into bukkits[] ?