【问题标题】:Calling cheerio.load inside each loop在每个循环中调用cheerio.load
【发布时间】:2015-09-23 08:59:26
【问题描述】:

所以Meteor中的基本服务器JS scraper

图案有点简单。脚本找到某些链接,然后从中加载内容并将内容存储在变量中。

在循环中加载cheerio 时脚本不断崩溃。 问题在哪里?为此目的最好的实现是什么?

  Meteor.methods({
    loadPage: function () {
      result = Meteor.http.get("http://url.com");
      $ = cheerio.load(result.content);
      $('.class').each(function(i,elem){
        var link = $(this).attr('href');
        var title = $(this).text();
        var $ = cheerio.load(Meteor.http.get(link).content);
        var postContent = $('.classOnLoadedPage');
        Images.insert(
          {
            link: link,
            title: title,
            postContent:  postContent
          });
      });
    }
  });

【问题讨论】:

  • 你得到什么错误?
  • @BidhanA Exception while invoking method 'loadPage' TypeError: undefined is not a function and points to "var link ..." inside loop, 但在我删除 cherio load inside loop 后一切正常。
  • requirecheerio 正确吗?
  • @BidhanA 是的)如果不在每个循环内部调用它,它就可以正常工作。
  • 尝试在$ = cheerio.load(result.content); 正下方添加console.log($) 以查看$ 是否有任何内容。

标签: node.js meteor web-scraping cheerio


【解决方案1】:

我今天遇到了完全相同的问题。原来这是cheerio本身的问题。它的旧版本有这个错误。您必须使用较新的版本,然后才能正常工作。

atmotejs 中下载最多的cheerio 包mrt:cheerio 包裹cheerio 0.12.3,而npm 中的当前版本是cheerio 0.19.0

添加rclai89:cheerio 而不是mrt:cheerio,它将提供cheerio 0.18.0,并且在循环内加载此版本时效果很好。

【讨论】:

    猜你喜欢
    • 2015-10-06
    • 2011-03-15
    • 1970-01-01
    • 2018-06-28
    • 2020-02-06
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    相关资源
    最近更新 更多