美文网首页
使用superagent 和cheerio完成简单点爬虫

使用superagent 和cheerio完成简单点爬虫

作者: 我该忘了我自己w_u | 来源:发表于2016-12-02 16:47 被阅读61次

    使用superagent 和cheerio完成简单点爬虫

    目的 访问 http://localhost:3000 ;
    输出 https://conodejs.org 的数据

    https://conodejs.org 源码

    2BAED63A-39E9-408F-B63E-14AAF3F59620.png

    最终效果

    353B8FE2-110B-4206-B18D-BEDD1CDFAD11.png
    • 用到的库 express,supragent cheerio
      -superagent是一个http方面的库
      -cheerio 是一个jquery一样的东西,作用是从网页中的css selector取数据。
    1. npm init
    2. npm install express supragent cheerio --save
    3. app.js
     superagent.get('https://cnodejs.org/') .end(function (err, sres) {
     // 常规的错误处理 
    if (err) { return next(err); } 
    // sres.text 里面存储着网页的 html 内容,将它传给 cheerio.load 之后// 就可以得到一个实现了 jquery 接口的变量,我们习惯性地将它命名为 `$` // 剩下就都是 jquery 的内容了
     var $ = cheerio.load(sres.text);
     var items = []; $('#topic_list .topic_title').each(function (idx, element) {
             var $element = $(element); 
             items.push({ 
                  title: $element.attr('title'), href:
                  $element.attr('href') 
                  });
     }); res.send(items); });
    });
    

    相关文章

      网友评论

          本文标题:使用superagent 和cheerio完成简单点爬虫

          本文链接:https://www.haomeiwen.com/subject/avlqmttx.html