用node.js写的http小爬虫

本文介绍了一个简单的HTTP爬虫程序,该程序用于抓取慕课网上特定课程的章节和视频信息。通过使用Node.js及cheerio库,实现了网页内容的解析,并展示了如何获取课程章节标题和对应的视频ID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值