nodejs

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')
})

===

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容