1. 程式人生 > >nodejs 之 小爬蟲

nodejs 之 小爬蟲

blue ole ext rip load err html brush title

一、簡單的單頁面
var http = require(‘http‘) var url = ‘http://www.imooc.com/learn/348‘ 
http.get(url,function(res){ 
  var html = ‘‘
    //有data觸發時
    res.on(‘data‘,function(data){
        html += data
    })
    res.on(‘end‘,function(){
        console.log(html)
    })
//出現異常時
}).on(‘error‘,function(){
    console.log(‘獲取出錯‘)
})

var server = http.createServer(function(req,res){
        res.writeHead(200,{‘Content-Type‘:‘text/plain‘})
        res.end();
    })
server.listen(2017)

  

運行結果

技術分享

二、獲取頁面的課程列表

安裝cheerio

cmd 執行命令 npm install cheerio 然後就可以require cheerio

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

//過濾頁面,獲取到列表的名稱與id等信息 與javascript方法一致 function filterChapters(html){ var $ = cheerio.load(html) // console.log($) 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, video:[] } // console.log(videos + ‘24‘) videos.each(function(item){ // var video = $(this).find(‘.studyvideo‘) var videoTitle = $(this).text() var id = $(this).attr("data-media-id") chapterData.video.push({ title:videoTitle, id:id }) }) courseData.push(chapterData) }) return courseData } //將獲取到的信息打印出來 function printCourseInfo(courseData) { courseData.forEach(function(item){ var chapterTitle = item.chapterTitle item.video.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(){ //過濾頁面信息 // console.log(html) var courseData = filterChapters(html) printCourseInfo(courseData) }) }).on(‘error‘,function(){ console.log(‘獲取出錯‘) }) var server = http.createServer(function(req,res){ res.writeHead(200,{‘Content-Type‘:‘text/plain‘}) res.end(); }) server.listen(1337)

運行結果

技術分享

nodejs 之 小爬蟲