NodeJs+Request+Cheerio 采集數據


目的:采集網站文章。

 

兩個依賴項:

request :https://github.com/request/request

cheerio:https://github.com/cheeriojs/cheerio

 

package.json文件:

{
"name":"zqz",
"version":"1.0.1",
"private":false,
"dependencies":{
"request":"*",
"cheerio":"*"
}
}

cdm中執行:npm install 進行安裝依賴的2個包。

 

app.js文件:

/**
* 數據采集
*/
//引入需要的包
var request = require('request');
var cheerio = require('cheerio');

//定義常量
var dolphin = 'http://cn.dolphin.com/blog';

//數據請求
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();

if($p)
{
console.info('--------------'+ (i+1) +' Chapter------------------');
console.info('標題:' + $aVal);
console.info('簡介:' + $pVal);
console.info('時間:' + new Date)
console.info('---------------------------------------------------');
}
}
}

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

 

Sublime 中 ctrl+B 執行

結果:

 


免責聲明!

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



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