0

我正在尝试使用RequestCheerio构建一个简单的网络爬虫。

现在的目标是抓取目标页面(在本例中为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[] ?
4

2 回答 2

2

本质上,您的整个程序现在必须在回调中进行。该回调之后的任何代码都无法访问异步检索并传递给回调的数据。

这并不像听起来那么糟糕。您可以使用命名函数,如下所示:

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.
}
于 2013-02-05T23:23:21.800 回答
0

您的代码在请求完成之前结束。

使用永久版本的代理

request = require('request').forever;

使用 setTimeout 来保持程序运行。

setTimeout(function(){}, 1000000);

要稍后使用这些值,还需要在请求调用完成后完成。

于 2013-02-05T23:19:47.527 回答