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

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

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

https://conodejs.org 源码

使用superagent 和cheerio完成简单点爬虫_第1张图片
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完成简单点爬虫)