Node.js :實(shí)現(xiàn)慕課網(wǎng)課程簡易爬蟲

使用cheerio模塊######

npm install cheerio



CODE:####

var http = require('http')
var cheerio = require('cheerio')
var url = 'http://www.imooc.com/learn/344'

function filterChapters(html){
    var $ = cheerio.load(html)
    var chapters = $('.chapter')

    var courseData = []

    chapters.each(function(item) {
        var chapter = $(this)
        var chapterTitle = chapter.find('strong').text()
        var 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(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 courseData = filterChapters(html)

        printCourseInfo(courseData)
    })
}).on('error', function() {
    console.log('獲取課程數(shù)據(jù)出錯(cuò)!')
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • cmd命令: ./ 當(dāng)前目錄 ../ 上一級(jí) dir 查看當(dāng)前目錄 ls 查看當(dāng)前目錄下文件 win...
    3hours閱讀 591評(píng)論 0 1
  • 目的 由于經(jīng)常會(huì)閱讀關(guān)于C++的博客,譬如Meeting C++!的blogroll、 reddit的r/cpp等...
    長不胖的Garfield閱讀 1,351評(píng)論 0 2
  • NPM 使用介紹 NPM是隨同NodeJS一起安裝的包管理工具,能解決NodeJS代碼部署上的很多問題,常見的使用...
    yyshang閱讀 445評(píng)論 0 1
  • 寫在前面: 前天,(是前天吧,,?)寫了一個(gè)基于http模塊和cheerio模塊實(shí)現(xiàn)的小爬蟲,爬取了慕課網(wǎng)的一些課...
    木木口丁閱讀 700評(píng)論 0 1
  • 上篇文章介紹了爬蟲的基本概念和基本原理,這篇開始我們一起來看看具體如何從網(wǎng)頁中爬取自己想要的數(shù)據(jù)。 在下面爬蟲的栗...
    特慈閱讀 352評(píng)論 0 0

友情鏈接更多精彩內(nèi)容