DIV CSS 佈局教程網

用 Node.js 依據 sitemap.xml 批次抓取圖片
編輯:JavaScript綜合知識     

本文介紹如何以 Node.js 讀取網站的 sitemap.xml,進而批次抓取站內圖片。相比逐頁硬爬,透過 sitemap 取得頁面清單會更有條理。這個版本特別加強了三個實用功能,並附上完整程式碼。

功能特色

  1. 可指定圖片要儲存到哪個目錄。
  2. 依文章分開建立子目錄存放,管理更清晰。
  3. 可設定同時下載的並行上限,避免請求過於頻繁。

package.json

這個工具依賴幾個常見套件:async 負責流程控制、cheerio 解析 HTML、mkdirp 建立目錄、request 發請求、xml2js 解析 XML。

{
  "name": "me2sex-images",
  "version": "0.0.1",
  "description": "Batch download images from a website via sitemap.xml",
  "main": "index.js",
  "author": "Fay",
  "license": "MIT",
  "dependencies": {
    "async": "^0.9.0",
    "cheerio": "^0.18.0",
    "mkdirp": "^0.5.0",
    "request": "^2.51.0",
    "url": "^0.10.2",
    "xml2js": "^0.4.4"
  }
}

index.js

主程式以 async.waterfall 串起「下載 sitemap → 解析為 JSON → 逐篇抓取圖片」三個階段,並透過 wrapTask 確保每個任務函式的上下文正確:

var node = {
  async: require('async'),
  cheerio: require('cheerio'),
  fs: require('fs'),
  mkdirp: require('mkdirp'),
  path: require('path'),
  request: require('request'),
  url: require('url'),
  xml2js: require('xml2js'),
};

var Me2SexImages = {
  /** 配置選項 */
  options: {
    sitemap: 'https://sexy.faceks.com/sitemap.xml', // 網站 sitemap 地址
    saveTo: '/Users/Fay/Pictures/me2sex',         // 保存到此文件夾
    downLimit: 5,                                  // 圖片並行下載上限
  },
  posts: [],

  /** 開始下載(程序入口函數) */
  start: function () {
    var self = this;
    var async = node.async;
    async.waterfall([
      self.wrapTask(self.sitemapXML),
      self.wrapTask(self.sitemapJSON),
      self.wrapTask(self.downAllImages),
    ], function (err, result) {
      if (err) {
        console.log('error: %s', err.message);
      } else {
        console.log('success: 下載成功');
      }
    });
  },

  /** 包裹任務,確保原任務的上下文指向某個特定對象 */
  wrapTask: function (task, context, exArgs) {
    var self = this;
    return function () {
      var args = [].slice.call(arguments);
      args = exArgs ? exArgs.concat(args) : args;
      task.apply(context || self, args);
    };
  },

  /** 獲取站點 sitemap.xml */
  sitemapXML: function (callback) {
    console.log('開始下載 sitemap.xml');
    node.request(this.options.sitemap, function (err, res, body) {
      if (!err) console.log('下載 sitemap.xml 成功');
      callback(err, body);
    });
  },

  /** 將 sitemap.xml 轉成 json */
  sitemapJSON: function (sitemapXML, callback) {
    var self = this;
    console.log('開始解析 sitemap.xml');
    node.xml2js.parseString(sitemapXML, { explicitArray: false }, function (err, json) {
      if (!err) {
        self.posts = json.urlset.url;
        self.posts.shift();
        console.log('解析 sitemap.xml 成功,共有 %d 個頁面', self.posts.length);
      }
      callback(err, self.posts);
    });
  },

  /** 下載整站圖片 */
  downAllImages: function (callback) {
    var self = this;
    var async = node.async;
    console.log('開始批量下載');
    async.eachSeries(self.posts, self.wrapTask(self.downPostImages), callback);
  },

  /** 下載單個 post 的圖片 */
  downPostImages: function (post, callback) {
    var self = this;
    var async = node.async;
    async.waterfall([
      self.wrapTask(self.mkdir, self, [post]),
      self.wrapTask(self.getPost),
      self.wrapTask(self.parsePost),
      self.wrapTask(self.downImages),
    ], callback);
  },

  mkdir: function (post, callback) {
    var path = node.path;
    var url = node.url.parse(post.loc);
    post.dir = path.join(this.options.saveTo, path.basename(url.pathname));
    console.log('準備創建目錄:%s', post.dir);
    if (node.fs.existsSync(post.dir)) {
      callback(null, post);
      console.log('目錄:%s 已經存在', post.dir);
      return;
    }
    node.mkdirp(post.dir, function (err) {
      callback(err, post);
      console.log('目錄:%s 創建成功', post.dir);
    });
  },

  /** 獲取 post 內容 */
  getPost: function (post, callback) {
    console.log('開始請求頁面:%s', post.loc);
    node.request(post.loc, function (err, res, body) {
      if (!err) post.html = body;
      callback(err, post);
      console.log('請求頁面成功:%s', post.loc);
    });
  },

  /** 解析 post,並獲取 post 中的圖片列表 */
  parsePost: function (post, callback) {
    var $ = post.$ = node.cheerio.load(post.html);
    post.images = $('.img')
      .map(function () { return $(this).attr('bigimgsrc'); })
      .toArray();
    callback(null, post);
  },

  /** 下載 post 圖片列表中的圖片 */
  downImages: function (post, callback) {
    console.log('發現 %d 張圖片,準備開始下載...', post.images.length);
    node.async.eachLimit(
      post.images,
      this.options.downLimit,
      this.wrapTask(this.downImage, this, [post]),
      callback
    );
  },

  /** 下載單個圖片 */
  downImage: function (post, imgsrc, callback) {
    var url = node.url.parse(imgsrc);
    var fileName = node.path.basename(url.pathname);
    var toPath = node.path.join(post.dir, fileName);
    console.log('開始下載圖片:%s,保存到:%s,文件名:%s', imgsrc, post.dir, fileName);
    node.request(imgsrc)
      .pipe(node.fs.createWriteStream(toPath))
      .on('close', function () {
        console.log('圖片下載成功:%s', imgsrc);
        callback();
      })
      .on('error', callback);
  }
};

Me2SexImages.start();

使用時只要修改 options 中的 sitemap 與 saveTo,再執行 node index.js 即可。透過 async.eachLimit 控制並行數,能有效避免一次發出過多請求而拖垮效能或被來源封鎖。以上就是完整內容,希望大家喜歡。

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