DIV CSS 佈局教程網

用 Node.js 寫一個批次下載圖片的爬蟲小工具
編輯:JavaScript綜合知識     

Node.js 雖然常被拿來做後端服務,但拿來寫爬蟲其實相當順手。本文以「批次下載圖片」為例,示範如何用 Node.js 抓取網頁內容、解析出圖片網址,再逐一存到本機,並附上可實作的完整程式碼。

使用步驟

  1. 建立一個名為 download 的目錄。
  2. 在該目錄下建立 download.js(檔名可自行決定)。
  3. 將本文的程式碼貼進 download.js 中。
  4. 開啟命令列工具,並把當前目錄切換到 download 目錄。
  5. 於命令列輸入:node download.js。
  6. 等待程式執行,圖片便會開始下載。

下載器主體(含斷點續傳支援)

以下用一個建構函式 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 的網路請求與檔案串流有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved