1箩艺、安裝5.0以上的node版本 #推薦使用nvm進(jìn)行node版本控制安裝node相應(yīng)版本遍搞,詳見:http://bubkoo.com/2017/01/08/quick-tip-multiple-versions-node-nvm/
2.項(xiàng)目根目錄下執(zhí)行 npm init 盲赊,然后一直回車即可? #如果node項(xiàng)目根目錄下沒有package.json的情況下盗迟,生成package.json
3劫侧、安裝所需模塊
npm install async --save
npm install cheerio --save
npm install superagent? --save
#async使用node的異步模塊谋国,各種用法詳見:https://github.com/ShaunLan/async
#cheerio將爬蟲獲取的HTML進(jìn)行解析,你可以像使用jQuery一樣的使用它
#superagent關(guān)于http的庫可以進(jìn)行http的get,post等請(qǐng)求
3号阿、爬蟲的過程分析:
① 使用superagent請(qǐng)求要爬蟲的網(wǎng)址
② 獲取到想要爬的HTML內(nèi)容使用cheerio進(jìn)行解析并鸵,再按jQuery獲取數(shù)據(jù)的方式從解析的數(shù)據(jù)中獲取到自己想要爬的數(shù)據(jù)
③ 如果想要并發(fā)異步的去請(qǐng)求要爬蟲的網(wǎng)址則使用async
#可參考:http://blog.didispace.com/nodejspachong/
4、實(shí)踐代碼
var superagent = require('superagent');
var cheerio = require('cheerio');
var async = require('async');
console.log('爬蟲程序開始運(yùn)行......');
superagent
?? ?//待抓取網(wǎng)頁
?? ?.get('http://www.shouce.ren/api/index')
?? ?//設(shè)置Header
?? ?.set('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8')
?? ?//返回結(jié)果值
?? ?.end(function(err, res){
?? ??? ?if(err || !res){
?? ??? ??? ?console.log('抓取數(shù)據(jù)失敗');
?? ??? ??? ?return ;
?? ??? ?}
?? ??? ?//解析返回html
?? ??? ?var $ = cheerio.load(res.text);
?? ??? ?var data = [];
?? ??? ?var host = 'www.shouce.ren';
?? ??? ?//遍歷獲取數(shù)據(jù)
?? ??? ?$('#bs-navbar-collapse .width-134').each(function(key, item){
?? ??? ??? ?var title = $(item).text();
?? ??? ??? ?var address = host + $(item).attr('href');
?? ??? ??? ?if(title.trim() && address.trim()){
?? ??? ??? ??? ?data.push({
?? ??? ??? ??? ??? ?'title' : title,
?? ??? ??? ??? ??? ?'address' : address
?? ??? ??? ??? ?});
?? ??? ??? ?}
?? ??? ?})
?? ??? ?var parallel_request_qty = 10;
?? ??? ?if(data.length > 0){
?? ??? ??? ?check_url_access(parallel_request_qty, data);
?? ??? ?}
?? ?});
//并發(fā)請(qǐng)求
function check_url_access(parallel_request_qty, data){
?? ?async.mapLimit(data, parallel_request_qty, function(item, callback){
?? ??? ?var addr = item.address;
?? ??? ?var name = item.title;
?? ??? ?superagent
?? ??? ??? ?.get(addr)
?? ??? ??? ?.set('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8')
?? ??? ??? ?.end(function(err, res){
?? ??? ??? ??? ?if(err || !res){
?? ??? ??? ??? ??? ?callback('訪問該URL失敗: ' + addr);
?? ??? ??? ??? ?} else {
?? ??? ??? ??? ??? ?console.log(
?? ??? ??? ??? ??? ??? ?'文檔名稱為:' + name +
?? ??? ??? ??? ??? ??? ?'扔涧,文檔地址為:' + addr +
?? ??? ??? ??? ??? ??? ?'园担,可以成功訪問'
?? ??? ??? ??? ??? ?);
?? ??? ??? ??? ??? ?callback(null, null);
?? ??? ??? ??? ?}
?? ??? ??? ?});
?? ?}, function(err, result){
?? ??? ?if(err){
?? ??? ??? ?console.log(err);
?? ??? ?}
?? ?})
}