nodejs写的一段扒css里面图片的代码(凑数,不然长草了)

/ 0评 / 0
var request = require('request')
  , fs = require('fs');
var cssList = []//目标css文件;

var Spider = function(targets) {
  this.targets = targets;
};

Spider.prototype = {
  constructor: Spider,
  init: function() {
    var self = this;
    var targets = this.targets;
    for (var i = 0, len = targets.length; i < len; i++) {
      var target = targets[i];
      request(target, function(err, response, body) {
        if (!err && response.statusCode == 200) {
          self.parseBody(body, target, function(realUrl, fileName) {
            self.downImage(realUrl, fileName);
          });
        } else {
          console.log(response.statusCode);
          console.log(err);
        }
      })
    }
  },
  parseBody: function(body, target, callback) {
    var res = body.match(/url((.*))/g);
    for(var j = 0; j < res.length; j++) {
      var r = res[j];
      var url = r.slice(4, r.length -1);
      var t = target.split('/');
      var tUrl = 'http:/',
        realUrl = '';
      for (var k = 1; k < t.length - 1; k++) {
        tUrl += t[k] + '/';
      }
      if (url.slice(0, 2) == '..') {
        realUrl = tUrl + url;
      }
      callback(realUrl, url.split('/')[2]);
    }
  },
  downImage: function(url, fileName) {
    if (url.length > 10) {
      request(url).pipe(fs.createWriteStream(fileName))
    }
  }
};

var spider = new Spider(cssList);
spider.init();

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注