NodeJs+http+fs+request+cheerio 采集,保存數據,並在網頁上展示(構建web服務器)


目的:

  數據采集

  寫入本地文件備份

  構建web服務器

  將文件讀取到網頁中進行展示

目錄結構:

package.json文件中的內容與上一篇一樣:NodeJs+Request+Cheerio 采集數據

request :https://github.com/request/request 使得請求變得更容易,簡單

cheerio:https://github.com/cheeriojs/cheerio 用來解析dom結構,類似jQuery,挺好用

app.js文件:

/**
 * 數據采集
 * 寫入本地文件備份
 * 創建web服務器
 * 將文件讀取到網頁中進行展示
 */
//引入需要的包
var http = require('http');
//var path = require('path');
var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');

//定義常量
var dolphin = 'http://cn.dolphin.com/blog';
const filePath = '/NodeJsTest/test_7/sampleCollection/localFiles/opts.txt';

//數據請求
function dataRequest(dataUrl) {
    //發送請求
    request({
        url : dataUrl,
        method : 'GET'
    },function(err, red, body) {
        //請求到body
        if(err){
            console.log(dataUrl);
            console.error('[ERROR]Collection' + err);        
            return;
        }

        if(dataUrl && dataUrl === dolphin){
            dataPraseDolphin(body);
        }
    })
}

/**
 * 解析html
 */
function dataPraseDolphin(body) {
    
    var $ = cheerio.load(body);

    var atricles = $('#content').children('.status-publish');

    for(var i = 0;i < atricles.length;i++){
        var article = atricles[i];

        var $a = $(article).find('.post-title .entry-title a');
        var $p = $(article).find('.post-content p');

        var $aVal = $($a).text();
        var $pVal = $($p).text();

        var localData;

        if($p){
            localData = '--------------'+ (i+1) +' Chapter------------------' + '\n'
                      + '標題:' + $aVal + '\n'
                      + '簡介:' + $pVal + '\n'
                      + '時間:' + new  Date + '\n'
                      + '---------------------------------------------------' + '\n';
            console.log(localData);
            writeToLocal(localData,i);
        }


    }
}

/**
 * [writeToLocal description]
 * 將解析的數據 寫入本地文件進行備份
 */
function writeToLocal(dataPage,fj){
    console.log('-------------准備寫入文件------------------------')
    //同步寫入文件,一般使用異步好
    fs.appendFileSync(filePath, dataPage);
}

/**
 * 創建web服務器
 * @return {[type]} [description]
 */
function createServer(){
    http.createServer(function(req,resp){

        console.log('服務啟動!')
        wirteToPage(resp);
        
    }).listen(7000);
}

/**
 * 將抓取的數據寫入頁面
 */
function wirteToPage(resp){
    fs.readFile(filePath,function(err,data){
        if(err){
            console.log(err);
            resp.writeHead(404,{
                'Content-Type':'text/html'
            })
        }else{
            resp.writeHead(200,{
                //響應頭添加編碼格式解決亂碼問題
                'Content-Type': 'text/plain;charset=utf-8'
            });
            //resp.write('<head><meta charset="utf-8"/></head>');      
            resp.write(data.toString());
        }
        resp.end();
    })
}

//開始發送請求 並 采集數據
dataRequest(dolphin);
createServer();

Sublime 中 ctrl+B 執行 

瀏覽器地址欄請求:http://localhost:7000

 結果

 

 


免責聲明!

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



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