仿教程 小爬蟲抓取imooc數據

 

慕課網的nodejs教程:http://www.imooc.com/learn/348html

這人講的很贊,特別是在事件驅動這點上,耳目一新。node

 

視頻略老,因此demo有些過期了,摸索着寫了一個本身的小程序。npm

比較痛苦的是最近半年幾乎沒寫過jQuery,很多用法實在想不起來,好在翻着API也不是什麼問題。json

 

首先,npm install cheerio,能夠認爲cheerio這貨就是nodejs版本的jQuery,用法應該徹底一致。小程序

而後就能夠愉快的敲代碼了:ide

var http = require('http')
var cheerio = require('cheerio')

var url = 'http://www.imooc.com/learn/348'

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

    var chapters = $('div.chapter')

    var courseData = []

    chapters.each(function () {
        var chapter=$(this) // $(this)的用法能夠讓回調方法省略參數
        // var chapterTitle = chapter.find('strong').text().trim()
        var chapterTitle = chapter.find('strong').contents().filter(function() { return this.nodeType === 3; }).text().trim(); 
        var videos=chapter.find('ul').children()
        var chapterData = { // 定義一個json以接收數據
            chapterTitle : chapterTitle,
            videos:[]
        }

        videos.each(function () {
            var video=$(this).find('a')
            var temp=video.text().trim()
            // var temp=video.contents().filter(function() { return this.nodeType === 3; }).text().trim(); 
            var arr = temp.split('\n') // 多層標籤的文本都拼到一塊兒了,要拆開,取用須要的值
            var videoTitle = arr[0].trim() + ' ' +arr[1].trim()
            var id=video.attr('href').split('video/')[1].trim()

            chapterData.videos.push({ // 填寫數據 
                title : videoTitle,
                id : id
            })
        })

        courseData.push(chapterData)
    })

    return courseData
}
// 輸出函數 
function printCourseData(courseData) {
    courseData.forEach(function (item) {
        var chapterTitle = item.chapterTitle

        console.log(chapterTitle )

        item.videos.forEach(function (video) {
            console.log('---【'+video.id + '】 ' + video.title.trim() )
        })
    })
}
// 拿到源碼,調用方法進行解析及輸出
http.get(url, function(res){
    var html = ''

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

    res.on('end',function(){
        var courseData = filterChapters(html)
        printCourseData(courseData)
    })
}).on('error', function () {
    console.log('獲取課程數據出錯了')
})
相關文章
相關標籤/搜索