Node.js 雖然常被拿來做後端服務,但拿來寫爬蟲其實相當順手。本文以「批次下載圖片」為例,示範如何用 Node.js 抓取網頁內容、解析出圖片網址,再逐一存到本機,並附上可實作的完整程式碼。
download 的目錄。download.js(檔名可自行決定)。download.js 中。download 目錄。node download.js。以下用一個建構函式 Mzitu 封裝整個流程,包含抓取列表頁、解析圖片網址、逐張下載等步驟:
var 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 _initialize(options) {
this.baseUrl = options.baseUrl;
this.dir = options.dir || '';
this.reg = options.reg;
this.total = options.total;
this.page = options.from || 1;
},
start: function _start() {
this.getPage();
},
getPage: function _getPage() {
var self = this, data = null;
if (this.page <= this.total) {
http.get(this.baseUrl + this.page, function (res) {
res.setEncoding("utf8");
res.on('data', function (chunk) {
data += chunk;
}).on('end', function () {
self.parseData(data);
});
});
}
},
parseData: function _parseData(data) {
var res = [], match;
while ((match = this.reg.exec(data)) != null) {
res.push(match[1]);
}
this.download(res);
},
download: function _download(resource) {
var self = this, currentPage = self.page;
resource.forEach(function (src, idx) {
var filename = src.substring(src.lastIndexOf('/') + 1),
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();
}
};
接著只要 new 出物件、傳入相關參數並呼叫 start() 即可。其中 baseUrl 是列表頁網址格式、reg 是用來比對圖片網址的正則表達式、total 是總頁數、from 是起始頁:
var mzitu = new Mzitu({
baseUrl: 'https://www.mzitu.com/share/comment-page-',
dir: '',
reg: /<imgs*src="(.*?)"s*alt=".*"s*/>/g,
total: 141,
from: 1
});
mzitu.start();
以上就是這個批次下載器的完整實作。你可以依需求替換 baseUrl 與 reg,讓它抓取不同來源的圖片資源。希望這個範例能對大家練習 Node.js 的網路請求與檔案串流有所幫助。