我正在尝试使用 Request 构建一个简单的网络爬虫和 Cheerio 。
现在的目标是抓取目标页面(在本例中为 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[] ?
最佳答案
本质上,您的整个程序现在必须在回调内进行。该回调之后的代码将无法访问异步检索并传递给回调的数据。
这并不像听起来那么糟糕。您可以使用命名函数,如下所示:
request(url, onRequestDone);
function onRequestDone(err, resp, body) {
var bukkits = []; // not global, make it local
// as above
doMoreWork(bukkits);
}
function doMoreWork(bukkits) {
// stuff after the parsing goes here.
}
关于javascript - 在 Node request() 中推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14718673/