nodejs 小爬虫

2016-12-20  本文已影响35人  jiangadam

nodejs 基础练习,爬取慕课网的某一个课程的内容
http 模块
cheerio 解析HTML的DOM结构

安装 cheerio

npm install cheerio
// 如果不行换淘宝的源
npm config set registry http://registry.npm.taobao.org
npm install cheerio
/**
 * nodejs 小爬虫基础练习,爬取慕课网的某一个课程的内容
 * 抓取慕课网的课程 URL = http://www.imooc.com/learn/348
 * @author= jiangadam
 */

var http = require('http')  // 加载http模块
var cheerio = require('cheerio')   // 加载cheerio模块
var url = "http://www.imooc.com/learn/348"

/**
 * 解析HTML的DOM结构  cheerio
 */
function filterChapter(html){
    var $ = cheerio.load(html)  // cheerio 的 load 方法将加载HTML结构

    var chapters = $('.chapter ')  // 课程内容的 class

    var data = []

    // 遍历
    chapters.each(function(item){
        var chapter = $(this)
        var chapterTitle = chapter.find('strong').text()

        var videos = chapter.find('.video').children('li')

        var chapterData = {
            // 去除换行符和空格
            chapterTitle: chapterTitle.replace(/\r|\n/ig,"").replace(/[ ]/g,""),
            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.replace(/\r|\n/ig,"").replace(/[ ]/g,""),
                id: id
            })
        })

        data.push(chapterData)
    })

    return data
}

// 遍历输出最后的结构
function printChapterData(data){
    data.forEach(function(item){
        console.log(item.chapterTitle)

        item.videos.forEach(function(item){
            console.log('id->' + item.id + ' title->' + item.title)
        })
    })
}

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

    response.on("end", function(){
        var data = filterChapter(html)
        printChapterData(data)
    })
})
上一篇下一篇

猜你喜欢

热点阅读