将基于 cheerio 的搜索循环添加到 node-simplecrawler

Add cheerio-based search loop to node-simplecrawler

我正在使用 node-simplecrawler 抓取一个网站,我需要在每个页面的特定 div 中搜索特定属性值。

simplecrawler 文档建议使用以下结构来完成此类任务:

myCrawler.on("fetchcomplete",function(queueItem,data,res) {
  var continue = this.wait();
  doSomeDiscovery(data,function(foundURLs){
    foundURLs.forEach(crawler.queueURL.bind(crawler));
    continue();
  });
});

我试了又试,但无法确定将我的基于 Cheerio 的搜索代码片段插入该结构的确切位置和方法。真的非常感谢这里的一些帮助。

var $ = cheerio.load(html);
$('div#jsid-post-container').each(function(i, element){
var StuffINeedToFetch = $(this).attr('data-external-id').text;

其实没必要搞乱 doSomeDiscovery。解决方案是直接使用响应缓冲区内容:

myCrawler.on("fetchcomplete",function(queueItem, responseBuffer){
    html = responseBuffer.toString();
    var $ = cheerio.load(html);
    $('div#jsid-post-container').each(function(i, element){
    var StuffINeedToFetch = $(this).attr('data-external-id').text;
});