RequestとCheerioを使用して単純な webscraper を構築しようとしています。
現在の目標は、宛先ページ (この場合はhttp://bukk.it ) をスクレイピングし、ページのターゲット セレクターからテキストを取得して、他の関数で使用できる配列にプッシュすることです。
非同期で実行されていることは理解してrequest()
いますが、スクレイピングされたデータを関数の外部に表示する方法がわかりません。
example.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[] ?