nodejs爬虫

爬虫:把网页爬下来(发送http请求,保存返回的结果,通常是html),分析html拿到有用数据。html

1、获取页面源码

拿到http://www.imooc.com/learn/348的源码【日期20170329】jquery

var http=require('http');
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(){
                console.log(html);
        });
}).on('error',function(){
    console.log('获取课程数据出错');
});

二、分析获取html中有用数据

先安装一个模块cheerio,cheerio能够理解成一个 Node.js 版的 jquery。npm

npm install cheerio数组

var http=require('http');
var cheerio=require('cheerio');
var url='http://www.imooc.com/learn/348';
//分析用cheerio模块
function filterChapters(html){
    var $=cheerio.load(html);
    var chatpers=$('.chapter');//全部章节的数组
/*//指望的数据结构
    [{
        chapterTitle:'',
        videos:[
            title:'',
            id:''
        ]
    }]*/
    var courseData=[];
    chatpers.each(function(item){
        var chapter=$(this);
        var chapterTitle=chapter.find('strong').text();
        videos=chapter.find('.video').children('li');
        var chapterData={
            chapterTitle:chapterTitle,
            videos:[]
        };

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

        })
        courseData.push(chapterData);
    })
    return courseData;
}
/*打印方法*/
function printCourseInfo(courseData){
    courseData.forEach(function(item){
        var chapterTitle=item.chapterTitle;
        console.log(chapterTitle+'\n');
        item.videos.forEach(function(item){
            console.log('【'+item.id+'】'+item.title+'\n');
        })
    })
}

http.get(url,function(res){
        var html='';
        res.on('data',function    (data){
            html+=data;
        })

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

 

本文做者starof,因知识自己在变化,做者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/6639505.html有问题欢迎与我讨论,共同进步。数据结构

相关文章
相关标签/搜索