用node.js寫的http小爬蟲

今天在慕課網學習到的一個小的http爬蟲程序,還是蠻有意思的,分享一下。注意要安裝node.js(自帶 nmp),中間要用nmp引入cheerio。

/**
 * Created by lenovo on 2017-05-01.
 */
const http = require('http');
const url = 'http://www.imooc.com/learn/348';
const cheerio = require('cheerio');
function filterChapters(html){
    var $ = cheerio.load(html);
    var chapters = $('.chapter');
    var courseDate = [];
    chapters.each(function(item){
        var chapter = $(this);
        var chapterTitle = chapter.find('strong').text();
        var videos = chapter.find('.video').find('li');
        var chapterDate = {
            chapterTitle : chapterTitle,
            videos : []
        }
        videos.each(function(item){
            var video = $(this).find('.J-media-item');
            var videoTitle = video.text();
            var videoId = video.attr('href').split('video/')[1];
            chapterDate.videos.push({
                title : videoTitle,
                id : videoId
            })
        })
        courseDate.push(chapterDate);
    })
    return courseDate;
}
function printCourseDate(courseDate){
    courseDate.forEach(function(item){
        console.log(item.chapterTitle + '\n');
        item.videos.forEach(function(video){
            console.log('[' + video.id + ']' + video.title+'\n');
        })
    })
}
http.get(url,function(res){

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

    res.on('end',function(){

        var courseDate = filterChapters(html);
        printCourseDate(courseDate);
        // console.log(courseDate);

    })
}).on('error',function(){
    console.log('出錯了');
});

喝喝,展示一下爬到的數據:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章