用node.js实现http小爬虫

用node.js实现http小爬虫

这次我第一次写博客!

最近我在慕课网上面学习了nodejs的基础教程,参照一些小伙伴的代码,写出了如下http小爬虫。
关于代码的理解:
第一部分:基础模块是http
用http模块中的get方法。
第二部分:需要引入api
通过在命令行中输入npm install cheerio来引入插件。
通过filterChapters(html)来对get方法中得到html信息进行筛选。
然后通过printCouerseInfo(courseData)将数据在控制台中输出。

代码块

var http = require(‘http’);
var cheerio = require(‘cheerio’);
var url = ‘http://www.imooc.com/learn/348‘;

http.get(url, function (res){

  var html ='';
    res.on('data',function(data){
        html+=data;
    });
    res.on('end',function(){
        var courseData=filterChapters(html);
        printCouerseInfo(courseData);
    })
}).on('error',function(){
    console.log('获取课程数据出错');
});

function filterChapters(html){

var $=cheerio.load(html);
var chapter=$('.chapter');
var courseData=[];
chapter.each(function (item){

    var chapter=$(this);
    var chapterTitle =chapter.find('strong').text();
    var videos =chapter.find('.video').children('li');
    var chapterData ={
        chapterTitle:chapterTitle,
        video:[]
    };
    videos.each(function(item){
        var video =$(this).find('.J-media-item');
        var videoTitle =video.text();
        var id=video.attr('href').split('video/')[1];

        chapterData.video.push({
            title:videoTitle,
            id:id
        })
    });
    courseData.push(chapterData)
});
return courseData;}

courseData.forEach(function(item){

    var chapterTitle =item.chapterTitle;
    console.log(chapterTitle+"\n");
    item.video.forEach(function(video){
        console.log('['+video.id+'] '+video.title+'\n');
    });
});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值