nodejs之爬蟲網頁的信息

1."cheerio",一個nodeJS模塊,類似於jquery,可以將html頁面的char轉換爲document文檔對象,然後用類似於jquery的方式進行操作DOM
2.編寫crawler.js文件
3.在 crawler.js目錄下使用如下命令安裝cheerio: npm install cheerio

4.然後運行 crawler.js

//引進所需模塊
var  http    = require('http')
var  cheerio = require('cheerio')
var  url     = "http://www.imooc.com/learn/348"

//html分析、處理函數;需要安裝模塊 npm install cheerio

function filterChapters(html){
        var $ = cheerio.load(html)//加載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){

	//獲取html 
	var html = ''
	res.on('data',function(data){
		html += data
	})

	res.on('end',function(){
		//處理html
	var  courseData =  filterChapters(html)
	     printCourseInfo(courseData)
	})

}).on('error',function(){
   console.log('獲取課程出錯!')
})


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章