【问题标题】:Reducing Redundancy with NodeJS and Cheerio使用 NodeJS 和 Cheerio 减少冗余
【发布时间】:2017-12-01 19:58:00
【问题描述】:

我只是想知道如何减少这两个网络爬虫的冗余,因为我不希望它两次请求网站。我是新手,对语法不是很熟悉。这是代码的sn-p:

            request(website_url, function(err, resp, body) {
            var $ = cheerio.load(body);
            $('.title').each(function(){
                var title = $(this).children('h2').children('span').text();
                titles.push(title);
            });

        request(website_url, function(err, resp, body) {
            var $ = cheerio.load(body);
            $('.post-box-excerpt').each(function(){
                var caption = $(this).children('p').text();
                captions.push(caption);
            });

【问题讨论】:

    标签: jquery node.js web-scraping cheerio


    【解决方案1】:

    最简单的方法是对 api 进行一次调用:

    request(website_url, function (err, resp, body) {
      var $ = cheerio.load(body);
    
      $('.title').each(function () {
        var title = $(this).children('h2').children('span').text();
        titles.push(title);
      });
    
      $('.post-box-excerpt').each(function () {
        var caption = $(this).children('p').text();
        captions.push(caption);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多