萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Node.js 批量下載圖片實戰:妹子圖爬蟲完整代碼

使用 Node.js 實現批量下載圖片,針對特定網站(如妹子圖)編寫爬蟲,支持分頁抓取、斷點續傳、並發控制。本文提供完整可運行代碼與使用教程。

使用步驟

  1. 創建 download 目錄
  2. 創建 download.js 腳本文件
  3. 複製兩段核心代碼
  4. 命令行進入目錄執行 node download.js
  5. 等待圖片自動下載完成

核心代碼: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(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="..." 中的 URL
  • 遞歸分頁,順序下載(可改為併發池控制並發數)
  • 文件名取 URL 最後一段
  • 支持斷點續傳(記錄 page 和 id)

改進建議

  • 使用 async/await + Promise 重寫回調地獄
  • 引入 axios/request-promise 簡化 HTTP
  • 添加並發限制(如 p-limit)防止過載
  • 完善錯誤重試、User-Agent 偽裝、Referer 設置
  • 遵守 robots.txt 與網站服務條款,合法合規爬取

法律提醒: 爬蟲僅供學習研究,商業用途需獲授權,尊重版權與反爬策略。

copyright © 萬盛學電腦網 all rights reserved