前言
前端時間再回顧了一下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/


