图片网站往往广告众多,用Node.js写个爬虫下载图片,代码不长,省事不少,比手动一张张保存简直是天与地的区别。
下面代码是一个从mtl.ttsqgs.com下载图片的程序,图片地址是看网站源码看出来的,总共有多少张也可以再源码里找到,然后就是按图索骥。
// 内置http模块,提供了http服务器和客户端功能var http=require("http");// cheerio模块,提供了类似jQuery的功能var cheerio = require("cheerio");// 内置文件处理模块var fs=require(‘fs‘);// 请求参数JSONvar options;// 请求并获得数据var req;// 存储页码var index=1;function downloadImg(pageNumber){ ???console.log("开始读取第"+pageNumber+"页"); ???// http://mtl.ttsqgs.com/images/img/7957/4.jpg // 实际图片地址 ???options={ ???????hostname:‘mtl.ttsqgs.com‘,// 这里别加http://,否则会出现ENOTFOUND错误 ???????????port:80, ???????????path:‘/images/img/7957/‘+pageNumber+‘.jpg‘,// 子路径 ?????????method:‘GET‘, ???}; ???????req=http.request(options,function(resp){ ???????var imgData = ""; ???????resp.setEncoding("binary"); ????????resp.on(‘data‘,function(chunk){ ???????????imgData+=chunk; ???????????????????}); ???????resp.on(‘end‘,function(){ ???????????fs.writeFile("./imgs/"+pageNumber+".jpg", imgData, "binary", function(err){ ???????????????if(err){ ???????????????????console.log("文件下载失败."); ???????????????} ???????????????console.log("下载成功"); ???????????}); ???????????}); ???}); ???// 超时处理 ???req.setTimeout(5000,function(){ ???????req.abort(); ???}); ???// 出错处理 ???req.on(‘error‘,function(err){ ???????if(err.code=="ECONNRESET"){ ???????????console.log(‘socket端口连接超时。‘); ???????}else{ ???????????console.log(‘请求发生错误,err.code:‘+err.code); ???????} ???}); ???// 请求结束 ???req.end(); ???// 49页调完 ???if(index<49){ ???????????????index++; ???????console.log(‘继续第‘+index+‘页‘); ???????start(index); ???}}// 包一层函数function start(i){ ???downloadImg(i);}// 开始遍历start(index);
2017年9月30日10:43:27
Node.js 使用爬虫批量下载网络图片到本地
原文地址:http://www.cnblogs.com/xiandedanteng/p/7614051.html