標籤:ade npm 屏蔽 gettime == preview callback 核心 strong
前言
前端時間再回顧了一下node.js,於是順勢做了一個爬蟲來加深自己對node的理解。
主要用的到是request,cheerio,async三個模組
request
用於請求地址和快速下載圖片流。
https://github.com/request/request
cheerio
為伺服器特別定製的,快速、靈活、實施的jQuery核心實現.
便於解析html代碼。
https://www.npmjs.com/package/cheerio
async
非同步呼叫,防止堵塞。
http://caolan.github.io/async/
核心思路
- 用request 發送一個請求。擷取html代碼,取得其中的img標籤和a標籤。
- 通過擷取的a表情進行遞迴調用。不斷擷取img地址和a地址,繼續遞迴
- 擷取img地址通過request(photo).pipe(fs.createWriteStream(dir + “/” + filename));進行快速下載。
function requestall(url) { request({ uri: url, headers: setting.header }, function (error, response, body) { if (error) { console.log(error); } else { console.log(response.statusCode); if (!error && response.statusCode == 200) { var $ = cheerio.load(body); var photos = []; $(‘img‘).each(function () { // 判斷地址是否存在 if ($(this).attr(‘src‘)) { var src = $(this).attr(‘src‘); var end = src.substr(-4, 4).toLowerCase(); if (end == ‘.jpg‘ || end == ‘.png‘ || end == ‘.jpeg‘) { if (IsURL(src)) { photos.push(src); } } } }); downloadImg(photos, dir, setting.download_v); // 遞迴爬蟲 $(‘a‘).each(function () { var murl = $(this).attr(‘href‘); if (IsURL(murl)) { setTimeout(function () { fetchre(murl); }, timeout); timeout += setting.ajax_timeout; } else { setTimeout(function () { fetchre("http://www.ivsky.com/" + murl); }, timeout); timeout += setting.ajax_timeout; } }) } } });}
防坑
1.在request通過圖片地址下載時,綁定error事件防止爬蟲異常的中斷。
2.通過async的mapLimit限制並發。
3.加入請求前序,防止ip被屏蔽。
4.擷取一些圖片和超連結位址,可能是相對路徑(待考慮解決是否有通過方法)。
function downloadImg(photos, dir, asyncNum) { console.log("即將非同步並發下載圖片,當前並發數為:" + asyncNum); async.mapLimit(photos, asyncNum, function (photo, callback) { var filename = (new Date().getTime()) + photo.substr(-4, 4); if (filename) { console.log(‘正在下載‘ + photo); // 預設 // fs.createWriteStream(dir + "/" + filename) // 防止pipe錯誤 request(photo) .on(‘error‘, function (err) { console.log(err); }) .pipe(fs.createWriteStream(dir + "/" + filename)); console.log(‘下載完成‘); callback(null, filename); } }, function (err, result) { if (err) { console.log(err); } else { console.log(" all right ! "); console.log(result); } })}
測試:
可以感覺到速度還是比較快的。
完整地址。https://github.com/hua1995116/node-crawler/
基於nodejs 的多頁面爬蟲