Node.js實現單頁面爬蟲

來源:互聯網
上載者:User

標籤:nodejs、爬蟲

    在imooc網上跟著老師寫了兩個爬蟲,一個最簡單的直接爬整個頁面,一個完善版把章區段標頭和對應編號打出來了。

    看完之後,自己也想寫一個爬蟲,用自己的部落格做測試,雖然結果並沒有很成功- -,還是把代碼放上來。

    目標是抓取章節的標題。


    部落格頁面:

650) this.width=650;" src="http://s1.51cto.com/wyfs02/M01/84/80/wKiom1eSLTqyNsHGAAE3M29Z1FA645.png" style="float:none;" title="3.png" alt="wKiom1eSLTqyNsHGAAE3M29Z1FA645.png" />


對應標籤:

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/84/80/wKioL1eSLTuzNUiTAABghDqCuL4871.png" style="float:none;" title="5.png" alt="wKioL1eSLTuzNUiTAABghDqCuL4871.png" />


頁面原始碼:

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/84/80/wKiom1eSLTvz4bj1AADp9_9EH8Y365.png" title="4.png" style="float:none;" alt="wKiom1eSLTvz4bj1AADp9_9EH8Y365.png" />


    經過分析,我們應該要抓取class=artHead的<div>,往下還有一個沒有類的<div>,然後找到它的<h3>標籤下子標籤<a>的內容,就是章節的名字。


    上代碼:

//引入http模組var http = require(‘http‘);//確定要抓取的頁面 //debug:本來寫了qmkkd.blog.51cto.com,一直出錯,在前面加上http就好了。var url = ‘‘;//這裡的url是‘http://qmkkd.blog.51cto.com‘;,部落格顯示不出來,有毒  //引入cherrio模組,類似伺服器端的jqueryvar cheerio=require(‘cheerio‘);function filterChapters(html){//將html變成jquery對象var $ = cheerio.load(html);var artHeads = $(‘.artHead‘);var blogData=[];artHeads.each(function(item){var artHead = $(this);//擷取文章標題var artTitle = artHead.find(‘h3‘).children(‘a‘).text();blogData.push(artTitle);})return blogData;}function printBlogInfo(blogData){blogData.forEach(function(item){var artTitle = item;console.log(item+‘\n‘);})}http.get(url,function(res){var buffers=[];var nread = 0;res.on(‘data‘,function(data){buffers.push(data);nread+=data.length;});//網上找到的處理中文亂碼問題的方法,但好像沒有解決T_T//之後還採用了bufferhelper類,好像也不對=-= //應該是基礎不好的問題,暫時debug不了,先放著res.on(‘end‘,function(){var buffer =null;switch(buffers.length){case 0:buffer=new Buffer(0);break;case 1:buffer=buffers[0];break;default:buffer = new Buffer(nread);for(var i=0,pos=0,l=buffers.length;i<l;i++){var chunk = buffers[i];chunk.copy(buffer,pos);pos+=chunk.length;}break;}var html=buffer.toString();var blogData = filterChapters(html);printBlogInfo(blogData);})}).on(‘error‘,function(){   //執行http請求失敗時,返回錯誤資訊console.log(‘擷取部落格資料出錯‘);})

    

本文出自 “Sunny” 部落格,請務必保留此出處http://qmkkd.blog.51cto.com/9511687/1828974

Node.js實現單頁面爬蟲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.