NodeJS學習:爬蟲小探



說明:本文在個人博客地址為edwardesire.com,歡迎前來品嘗。


今天來學習alsotang的爬蟲教程,跟着把CNode簡單地爬一遍。


  1. 建立項目craelr-demo
    我們首先建立一個Express項目,然后將app.js的文件內容全部刪除,因為我們暫時不需要在Web端展示內容。當然我們也可以在空文件夾下直接 npm install express來使用我們需要的Express功能。

  2. 目標網站分析
    如圖,這是CNode首頁一部分div標簽,我們就是通過這一系列的id、class來定位我們需要的信息。

  3. 使用superagent獲取源數據
    superagent就是ajax API來使用的Http庫,它的使用方法與jQuery差不多,我們通過它發起get請求,在回調函數中輸出結果。

     var express = require('express');
     var url = require('url'); //解析操作url
     var superagent = require('superagent'); //這三個外部依賴不要忘記npm install
     var cheerio = require('cheerio');
     var eventproxy = require('eventproxy');
    
     var targetUrl = 'https://cnodejs.org/';
     superagent.get(targetUrl)
         .end(function (err, res) {
             console.log(res);
         });
    

    它的res結果為一個包含目標url信息的對象,網站內容主要在其text(string)里。

  4. 使用cheerio解析
    cheerio充當服務器端的jQuery功能,我們先使用它的.load()來載入HTML,再通過CSS selector來篩選元素。

     var $ = cheerio.load(res.text);
     //通過CSS selector來篩選數據
     $('#topic_list .topic_title').each(function (idx, element) {
         console.log(element);
     });
    

    其結果為一個個對象,調用 .each(function(index, element))函數來遍歷每一個對象,返回的是HTML DOM Elements。

    輸出 console.log($element.attr('title'));的結果為 廣州 2014年12月06日 NodeParty 之 UC 場
    之類的標題,輸出 console.log($element.attr('href'));的結果為 /topic/545c395becbcb78265856eb2之類的url。再用NodeJS1的url.resolve()函數來補全完整的url。

     superagent.get(tUrl)
         .end(function (err, res) {
             if (err) {
                 return console.error(err);
             }
             var topicUrls = [];
             var $ = cheerio.load(res.text);
             // 獲取首頁所有的鏈接
             $('#topic_list .topic_title').each(function (idx, element) {
                 var $element = $(element);
                 var href = url.resolve(tUrl, $element.attr('href'));
                 console.log(href);
                 //topicUrls.push(href);
             });
         });
    
  5. 使用eventproxy來並發抓取每個主題的內容
    教程上展示了深度嵌套(串行)方法和計數器方法的例子,eventproxy就是使用事件(並行)方法來解決這個問題。當所有的抓取完成后,eventproxy接收到事件消息自動幫你調用處理函數。

     //第一步:得到一個 eventproxy 的實例
     var ep = new eventproxy();
    
     //第二步:定義監聽事件的回調函數。
     //after方法為重復監聽
     //params: eventname(String) 事件名,times(Number) 監聽次數, callback 回調函數
     ep.after('topic_html', topicUrls.length, function(topics){
         // topics 是個數組,包含了 40 次 ep.emit('topic_html', pair) 中的那 40 個 pair
         //.map
         topics = topics.map(function(topicPair){
             //use cheerio
             var topicUrl = topicPair[0];
             var topicHtml = topicPair[1];
             var $ = cheerio.load(topicHtml);
             return ({
                 title: $('.topic_full_title').text().trim(),
                 href: topicUrl,
                 comment1: $('.reply_content').eq(0).text().trim()
             });
         });
    
         //outcome
         console.log('outcome:');
         console.log(topics);
     });
    
     //第三步:確定放出事件消息的
     topicUrls.forEach(function (topicUrl) {
         superagent.get(topicUrl)
             .end(function (err, res) {
                 console.log('fetch ' + topicUrl + ' successful');
                 ep.emit('topic_html', [topicUrl, res.text]);
             });
     });
    

    結果如下

  6. 擴展練習(挑戰)

    • 獲取留言用戶名和積分

    在文章頁面的源碼找到評論的用戶class名,classname為reply_author。console.log第一個元素 $('.reply_author').get(0)可以看到,我們需要獲取東西都在這里頭。

    首先,我們先對一篇文章進行抓取,一次性把需要的都得到即可。

     var userHref = url.resolve(tUrl, $('.reply_author').get(0).attribs.href);
     console.log(userHref);
     console.log($('.reply_author').get(0).children[0].data);
    

    我們可以通過https://cnodejs.org/user/username抓取積分信息

     $('.reply_author').each(function (idx, element) {
    		var $element = $(element);
     	console.log($element.attr('href'));
     });
    

    在用戶信息頁面 $('.big').text().trim()即為積分信息。

    使用cheerio的函數.get(0)為獲取第一個元素。

     var userHref = url.resolve(tUrl, $('.reply_author').get(0).attribs.href);
     console.log(userHref);
    

    這只是對於單個文章的抓取,對於40個還有需要修改的地方。


Notes:

  1. 爬蟲定義
  2. superagent
  3. cheerio
  4. Ajax
  5. jQuery
  6. 30種CSS Selectors
  7. eventproxy


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM