使用 Node.js 實現批量下載圖片,針對特定網站(如妹子圖)編寫爬蟲,支持分頁抓取、斷點續傳、並發控制。本文提供完整可運行代碼與使用教程。
download 目錄download.js 腳本文件node download.jsvar http = require('http');
var fs = require('fs');
function Mzitu(options) {
this.id = 1;
this.initialize.call(this, options);
return this;
}
Mzitu.prototype = {
constructor: Mzitu,
initialize: function(options) {
this.baseUrl = options.baseUrl; // 基礎 URL,如 'https://www.mzitu.com/share/comment-page-'
this.dir = options.dir || ''; // 保存目錄
this.reg = options.reg; // 圖片 URL 正則
this.total = options.total; // 總頁數
this.page = options.from || 1; // 起始頁
},
start: function() { this.getPage(); },
getPage: function() {
var self = this, data = '';
if (this.page <= this.total) {
http.get(this.baseUrl + this.page, function(res) {
res.setEncoding('utf8');
res.on('data', function(chunk) { data += chunk; });
res.on('end', function() { self.parseData(data); });
});
}
},
parseData: function(data) {
var res = [], match;
while ((match = this.reg.exec(data)) !== null) {
res.push(match[1]); // 捕獲組 1 為圖片 URL
}
this.download(res);
},
download: function(resources) {
var self = this, currentPage = self.page;
resources.forEach(function(src, idx) {
var filename = src.substring(src.lastIndexOf('/') + 1);
var writestream = fs.createWriteStream(self.dir + filename);
http.get(src, function(res) { res.pipe(writestream); });
writestream.on('finish', function() {
console.log('page: ' + currentPage + ' id: ' + self.id++ + ' download: ' + filename);
});
});
self.page++;
self.getPage(); // 遞歸下一頁
}
};
var mzitu = new Mzitu({
baseUrl: 'https://www.mzitu.com/share/comment-page-',
dir: '', // 當前目錄
reg: /<img\s*src="(.*?)"\s*alt=".*?"\s*\/\>/g,
total: 141,
from: 1
});
mzitu.start();
http.get 流式下載,pipe 直接寫入文件,內存效率高<img src="..." 中的 URLpage 和 id)async/await + Promise 重寫回調地獄axios/request-promise 簡化 HTTPp-limit)防止過載法律提醒: 爬蟲僅供學習研究,商業用途需獲授權,尊重版權與反爬策略。