Nodejs实现批量下载妹纸图
听说最近下载妹子图很火?
Nodejs(javascrpt)自然不能落后~
虽然从没写过像样的Nodejs程序,但作为至少翻过书的前端同学来说,Nodejs用得还蛮顺手的哈~
花了一点事件学习了下Nodejs的网页获取和文件下载方法,没事乱捣腾就写了这个半成品的下载器
使用方法:
1)新建一个download目录
2)新建download.js(其实名字随便取),并复制到download目录下
3)复制两段代码到download.js中
4)打开命令行工具,并将当前目录转到与download目录下
5)在命令行中输入:nodedownload.js
6)等着收妹子图吧~
简单的妹子图对象(新增断定下载支持)
varhttp=require('http');
varfs=require('fs');
functionMzitu(options){
this.id=1;
this.initialize.call(this,options);
returnthis;
}
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(){
varself=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){
varres=[],
match;
while((match=this.reg.exec(data))!=null){
res.push(match[1]);
}
this.download(res);
},
download:function_download(resource){
varself=this,
currentPage=self.page;
resource.forEach(function(src,idx){
varfilename=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();
}
};
妹子图下载启动方式
varmzitu=newMzitu({
baseUrl:'http://www.mzitu.com/share/comment-page-',
dir:'',
reg:/<img\s*src="(.*?)"\s*alt=".*"\s*\/>/g,
total:141,
from:1
});
mzitu.start();
以上所述就是本文的全部内容了,希望大家能够喜欢。