用node.js写的http小爬虫

来源:互联网 发布:淘宝选品数据分析 编辑:程序博客网 时间:2024/05/18 23:28

今天在慕课网学习到的一个小的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('出错了');});

喝喝,展示一下爬到的数据:
这里写图片描述

0 0
原创粉丝点击