nodejs

2016-11-16  本文已影响0人  poppyl

npm install cheerio'''

chinese:http://cnodejs.org/topic/5203a71844e76d216a727d2e
english:https://github.com/cheeriojs/cheerio


这个是和jQuery很想,可以对html进行处理
下面是一个慕课网网络爬虫的

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

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('get failed')
})

===

上一篇下一篇

猜你喜欢

热点阅读