標籤:node.js(九)——http小爬蟲
HTTP爬蟲
網路上每時每刻都有海量的請求,有從用戶端到伺服器端的,也有伺服器端到伺服器端的
一般在瀏覽器裡,我們是通過ajax來完成表單的提交或者是資料的擷取,
那在http模組裡呢get和request這兩個介面來完成資料的擷取或者是提交。
來個執行個體,爬一下51cto部落格的資料
先從最簡單的爬蟲開始,爬源碼
範例程式碼如下:
var http = require(‘http‘)var url = ‘http://mazongfei.blog.51cto.com/3174958/1909817‘http.get(url, function(res){var html = ‘‘res.on(‘data‘,function(data){html += data})res.on(‘end‘,function(){console.log(html)}).on(‘error‘,function(){console.log(‘擷取部落格頁面出錯‘)})})
運行結果態度,截取一段如下:
650) this.width=650;" src="https://s4.51cto.com/wyfs02/M02/8F/29/wKiom1jVEVPS4dLqAACouMTBZBY575.jpg" title="36020170315204858576.jpg" alt="wKiom1jVEVPS4dLqAACouMTBZBY575.jpg" />源碼雖然爬下來了,但是對我們來說沒有多大意義,我們想拿到部落格的標題資訊,(因知識儲備不夠,未能爬到部落格的代碼,初步理解是Reboot檔案)改爬慕課網
那這個時候就需要我們分析源碼,把有價值的東西給篩選出來;
我們怎麼對源碼進行分析呢,這裡推薦一個模組:cherio
它就像jquery一樣能夠操作裝載後台html,簡單而又方便
首先先安裝一下該模組: npm install cheerio
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 = $(‘.chapter‘)//我們想拿到一個數組,格式如下:/*[{chapterTitle:‘‘,videos:[title:‘‘,id:‘‘]}]*/var courseData = []//遍曆的裡面拿到資料chapters.each(function(item){var chapter = $(this);//章區段標頭var chapterTitle = chapter.find(‘strong‘).text()console.log(chapterTitle)var videos = chapter.find(‘.video‘).children(‘li‘)var chapterData = {chapterTitle:chapterTitle,videos:[]}//遍曆videosvideos.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.chapterTitleitem.videos.forEach(function(video){console.log(‘【‘+video.id+‘】‘+video.title);})})}http.get(url, function(res){var html = ‘‘res.on(‘data‘,function(data){html += data})res.on(‘end‘,function(){//處理var courseData = filterChapters(html)printCourseInfo(courseData)}).on(‘error‘,function(){console.log(‘擷取頁面出錯‘)})})
運行結果如下:
650) this.width=650;" src="https://s2.51cto.com/wyfs02/M02/8F/2A/wKioL1jV4HzCrLcxAAAjTshuyZE359.jpg" title="36020170315204858576.jpg" alt="wKioL1jV4HzCrLcxAAAjTshuyZE359.jpg" />
如果出錯,進行console.log進行調試
有了編號,我們就可以自己組裝url地址【6712】並單獨訪問每一節的內容,
可以做更多的事情,目前爬蟲代碼先到此為止。
但還有另外一個問題:如果把每一節的內容都跑出來的話,
在代碼中的表現形式都是回調,在此只拿課程首頁這個內容,
如果去請求每一節的內容的話是非同步不一定是多長時間可以拿到內容,
所以是回調的話,就是一個不知時間長短的回調;所以就有一種非同步
的回調編程方式,來讓我們組裝好隊列,得到我們想要的結果
本文出自 “IT菜鳥” 部落格,請務必保留此出處http://mazongfei.blog.51cto.com/3174958/1910188
Node.js(九)——HTTP小爬蟲