DIV CSS 佈局教程網

用 Node.js 依 sitemap.xml 批次下載圖片
編輯:關於JavaScript     

需要把某個網站的圖片整批抓下來時,逐頁點擊右鍵另存顯然不現實。如果目標站點有提供 sitemap.xml,就可以拿它當作「頁面清單」,再逐頁解析、把圖片收集起來下載。本文用 Node.js 實作這樣一個批次下載器,重點不在於目標網站,而在於整個流程的組織方式。

功能設計

  • 可指定下載後的存放目錄。
  • 以「一篇文章一個子目錄」的方式分類存放,避免檔案全部堆在一起。
  • 可設定並行下載上限,避免同時開太多連線被對方限流。

package.json

{
  "name": "sitemap-image-downloader",
  "version": "0.0.1",
  "description": "Batch download images listed in a sitemap.xml",
  "main": "index.js",
  "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

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 ImageDownloader = {

    /** 設定選項 */
    options: {
        sitemap:   'https://example.com/sitemap.xml', // sitemap 位址
        saveTo:    '/Users/me/Pictures/downloaded',  // 存檔目錄
        downLimit: 5,                                // 並行下載上限
    },

    posts: [],

    /** 程式入口 */
    start: function () {
        var self = this;
        node.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: 下載完成');
            }
        });
    },

    /**
     * 包裝任務,確保任務函數的 this 指向特定物件
     * @param {Function} task 符合 async.js 呼叫方式的任務函數
     * @param {Any} context 上下文
     * @param {Array} exArgs 額外參數
     */
    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('解析完成,共有 %d 個頁面', self.posts.length);
            }
            callback(err, self.posts);
        });
    },

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

    /** 下載單篇文章的圖片 */
    downPostImages: function (post, callback) {
        var self = this;
        node.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)) {
            console.log('目錄 %s 已存在', post.dir);
            callback(null, post);
            return;
        }
        node.mkdirp(post.dir, function (err) {
            callback(err, post);
            console.log('目錄 %s 建立成功', post.dir);
        });
    },

    /** 抓取文章內容 */
    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);
        });
    },

    /** 解析文章,取出圖片清單 */
    parsePost: function (post, callback) {
        var $ = post.$ = node.cheerio.load(post.html);
        post.images = $('.img')
            .map(function () { return $(this).attr('bigimgsrc'); })
            .toArray();
        callback(null, 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', imgsrc, toPath);
        node.request(imgsrc)
            .pipe(node.fs.createWriteStream(toPath))
            .on('close', function () {
                console.log('圖片下載成功:%s', imgsrc);
                callback();
            })
            .on('error', callback);
    }
};

ImageDownloader.start();

幾個關鍵設計點

async.waterfall 串起流程。下載 sitemap、解析 XML、逐篇抓取,這幾步有嚴格先後順序,用 waterfall 能把每一步的輸出自動當成下一步的輸入,不必寫一層又一層的 callback。

wrapTask 解決 this 指向。把方法當成 callback 傳出去時 this 會跑掉,包一層 apply 就能保住上下文;需要預先塞入參數時,用第三個參數 exArgs 前置合併即可。

eachSeries 與 eachLimit 的分工。文章之間用 eachSeries 循序處理,降低對目標站的壓力;同一篇文章內的圖片則用 eachLimit 控制在 5 個以內並行,兼顧速度與禮貌。

實務上還建議加上 User-Agent 標頭、失敗重試與去重(同一張圖已存在就跳過)。抓取他人網站內容前,也請先確認 robots.txt 與使用條款,並控制請求頻率,避免造成對方服務負擔。

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