码迷,mamicode.com
首页 > Web开发 > 详细

node.js 使用 superagent 与 cheerio 完成简单爬虫

时间:2017-04-22 19:45:16      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:css   应用   知识   auth   sso   安装   数据   http   func   

目标

建立一个 lesson3 项目,在其中编写代码。

当在浏览器中访问 http://localhost:3000/ 时,输出 CNode(https://cnodejs.org/ ) 社区首页的所有帖子标题和链接,以 json 的形式

 

知识点:

  1. 学习使用 superagent 抓取网页
  2. 学习使用 cheerio 分析网页

 

库介绍:

superagent(http://visionmedia.github.io/superagent/ ) 是个 http 方面的库,可以发起 get 或 post 请求。

cheerio(https://github.com/cheeriojs/cheerio ) 大家可以理解成一个 Node.js 版的 jquery,用来从网页中以 css selector 取数据,使用方式跟 jquery 一样一样的。

创建项目相关命令:

  1. 新建一个文件夹,进去之后 npm init
  2. 安装依赖 npm install --save PACKAGE_NAME
  3. 写应用逻辑

安装2个库和express

nmp install --save express
nmp install --save superagent
nmp install --save cheerio

 

 

var superagent = require(‘superagent‘);
var express = require(‘express‘);
var cheerio = require(‘cheerio‘);



var app = express();

app.get(‘/‘, function(req, res, next ) {
    superagent.get(‘https://cnodejs.org/‘)
        .end( function( err, sres ) {
            if (err){
                return next(err);
            }

            var $ = cheerio.load(sres.text);
            var items = [];
               // sres.text 里面存储着网页的 html 内容,将它传给 cheerio.load 之后
               // 就可以得到一个实现了 jquery 接口的变量,我们习惯性地将它命名为 `$`
              // 剩下就都是 jquery 的内容了
            $(‘#topic_list .topic_title ‘).each(function(idx, element ){
                var $element = $(element);
                items.push({
                    title: $element.attr(‘title‘),
                    href: $element.attr(‘href‘)
                });
            });
            //new 
            $(‘#topic_list .user_avatar ‘).each(function(idx, element) {
                var $element = $(element);
                items[idx][‘author‘] = $element.attr(‘href‘).split(‘/‘)[2]
            });

            res.send(items);
        });
});




app.listen(3000, function (req, res) {
  console.log(‘app is running at port 3000‘);
});

 

node.js 使用 superagent 与 cheerio 完成简单爬虫

标签:css   应用   知识   auth   sso   安装   数据   http   func   

原文地址:http://www.cnblogs.com/chenjf/p/6748817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!