Node.js mimimn图片批量下载爬虫 1.00
这个爬虫在Referer设置上和其它爬虫相比有特殊性。代码:
//====================================================== // mimimn图片批量下载Node.js爬虫1.00 // 2017年11月15日 //======================================================// 内置http模块 var https=require("https");// 内置文件处理模块,用于创建目录和图片文件 var fs=require('fs');// cheerio模块,提供了类似jQuery的功能,用于从HTML code中查找图片地址和下一页 var cheerio = require("cheerio");// 请求参数JSON。http和https都有使用 var options;// request请求 var req;// 图片数组,找到的图片地址会放到这里 var pictures=[];//-------------------------------------- // 爬取网页,找图片地址,再爬 // pageUrl sample:https://www.mimimn.com/files/38/3832.html // pageUrl sample:https://www.mimimn.com/files/37/3775.html //-------------------------------------- function crawl(pageUrl){console.log("Current page="+pageUrl);// 得到hostname和pathvar currUrl=pageUrl.replace("https://","");var pos=currUrl.indexOf("/");var hostname=currUrl.slice(0,pos); var path=currUrl.slice(pos); //console.log("hostname="+hostname);//console.log("path="+path);// 初始化options options={hostname:hostname,port:443,path:path,// 子路径method:'GET', };req=https.request(options,function(resp){var html = [];resp.on("data", function(data) {html.push(data);})resp.on("end", function() {var buffer = Buffer.concat(html);var body=buffer.toString();//console.log(body);var $ = cheerio.load(body); var picCount=0;// 找图片放入数组$(".text-center a img").each(function(index,element){var picUrl=$(element).attr("src");//console.log(picUrl);if(picUrl.indexOf('.jpg')!=-1){pictures.push(picUrl); picCount++;} }) console.log("找到图片"+picCount+"张."); // 找下一页var htmls=[];var currIndex=-1;$(".pagination ul li").each(function(index,element){var text=$(element).html();//console.log(text); htmls.push(text);var cls=$(element).attr("class");if(cls=='active'){currIndex=index; } })//console.log("htmls.length="+htmls.length);//console.log("currIndex="+currIndex);if((htmls.length-1)==currIndex){console.log(pageUrl+"已经是最后一页了.");download(pictures);}else{var text=htmls[currIndex+1];var start=text.indexOf("\"");var end=text.lastIndexOf("\"");var nextPageUrl=text.slice(start+1,end);//console.log("下一页是"+nextPageUrl); crawl(nextPageUrl);}}).on("error", function() {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(); }//-------------------------------------- // 下载图片 //-------------------------------------- function download(pictures){var folder='pictures('+getNowFormatDate()+")";// 创建目录fs.mkdir('./'+folder,function(err){if(err){console.log("目录"+folder+"已经存在");}});var total=0;total=pictures.length;console.log("总计有"+total+"张图片将被下载.");appendToLogfile(folder,"总计有"+total+"张图片将被下载.\n");for(var i=0;i<pictures.length;i++){var picUrl=pictures[i];downloadPic(picUrl,folder);} }//-------------------------------------- // 写log文件 //-------------------------------------- function appendToLogfile(folder,text){fs.appendFile('./'+folder+'/log.txt', text, function (err) {if(err){console.log("不能书写log文件");console.log(err);}}); }//-------------------------------------- // 取得当前时间 //-------------------------------------- function getNowFormatDate() {var date = new Date();var seperator1 = "-";var seperator2 = "_";var month = date.getMonth() + 1;var strDate = date.getDate();if (month >= 1 && month <= 9) {month = "0" + month;}if (strDate >= 0 && strDate <= 9) {strDate = "0" + strDate;}var currentdate =date.getFullYear() + seperator1 + month + seperator1 + strDate+ " " + date.getHours() + seperator2 + date.getMinutes()+ seperator2 + date.getSeconds();return currentdate; }//-------------------------------------- // 下载单张图片 // picUrl sample:https://mi.uz0.net/20171029/1509249915gi25.jpg //-------------------------------------- function downloadPic(picUrl,folder){console.log("图片:"+picUrl+"下载开始");// 得到hostname,path和portvar currUrl=picUrl.replace("https://","");var pos=currUrl.indexOf("/");var hostname=currUrl.slice(0,pos); var path=currUrl.slice(pos); //console.log("hostname="+hostname);//console.log("path="+path);var picName=currUrl.slice(currUrl.lastIndexOf("/"));// 初始化options options={hostname:hostname,port:443,path:path,// 子路径method:'GET',// HTTP请求中有一个referer的报文头,用来指明当前流量的来源参考页. headers:{'Referer':'https://www.mimimn.com',// 设置Referer,没有这一步图片下载不下来,因为网站用Rederer做了低端的图片防盗链 }};req=https.request(options,function(resp){var imgData = "";resp.setEncoding("binary"); resp.on('data',function(chunk){imgData+=chunk; });resp.on('end',function(){ // 创建文件var fileName="./"+folder+picName;fs.writeFile(fileName, imgData, "binary", function(err){if(err){console.log("[downloadPic]文件"+fileName+"下载失败.");console.log(err);appendToLogfile(folder,"文件 "+picUrl+" 下载失败.\n");}else{appendToLogfile(folder,"文件 "+picUrl+" 下载成功.\n");console.log("文件"+fileName+"下载成功");}}); });});// 超时处理req.setTimeout(7500,function(){req.abort();});// 出错处理req.on('error',function(err){if(err){console.log('[downloadPic]文件'+picUrl+"下载失败,"+'因为'+err);appendToLogfile(folder,"文件"+picUrl+"下载失败.\n");}});// 请求结束 req.end(); }//-------------------------------------- // 程序入口 //-------------------------------------- function getInput(){process.stdout.write("\033[35m 请输入第一页URL:\033[039m"); //紫色 process.stdin.resume();process.stdin.setEncoding('utf8'); process.stdin.on('data',function(text){process.stdin.end();// 退出输入状态 crawl(text.trim());// trim()是必须的! }); }// 调用getInput函数,程序开始 getInput();
关于Referer设置的参考文章如下:
http://blog.csdn.net/u011250882/article/details/49679535
https://www.cnblogs.com/rubylouvre/p/3541411.html
http://blog.csdn.net/fishmai/article/details/52388840
https://www.cnblogs.com/bukudekong/p/3829852.html
https://zhidao.baidu.com/question/1832550088624773020.html
2017年11月15日05:19:50
转载于:https://www.cnblogs.com/xiandedanteng/p/7837136.html
Node.js mimimn图片批量下载爬虫 1.00相关推荐
- Node.js monly图片批量下载爬虫1.00
此爬虫又用到了iconv转码,代码如下: //====================================================== // mmonly图片批量下载爬虫1.00 ...
- Node.js meitulu图片批量下载爬虫1.051
原有1.05版程序没有断点续传模式,现在在最近程序基础上改写一版1.051. //====================================================== // m ...
- Node.js aitaotu图片批量下载Node.js爬虫1.00版
即使是https网页,解析的方式也不是一致的,需要多试试. 代码: //====================================================== // aitaot ...
- Node.js umei图片批量下载Node.js爬虫1.00
这个爬虫在abaike爬虫的基础上改改图片路径和下一页路径就出来了,代码如下: //====================================================== // ...
- 【pyhon】nvshens图片批量下载爬虫1.01
# nvshens图片批量下载爬虫1.01 # 原先版本在遇到网络故障时回下载不全,这回更改了模式使得下载不成就重新下载,直到全部下载完毕 from bs4 import BeautifulSoup ...
- 【pyhon】怨灵侍全本漫画批量下载爬虫1.00
代码: # 怨灵侍全本漫画批量下载爬虫1.00 # 拜CARTOON.fydupiwu.com整理有序所赐,寻找图片只要观察出规律即可,不用费劲下一页的找了 import time import ur ...
- 【Chrome】图片批量下载扩展zzllrr Imager小乐图客V1.4 (支持正则表达式、自定义JS代码、自定义引擎、多网站取图规则)...
小乐图客 - Chrome浏览器图片批量下载工具,升级至V1.4 该版本实现的功能: 1.右下角集成众多网站引擎(相似图片搜索.图片搜索.网页搜索.图片上传等等). 2.选项中增加各类设置的重置.导入 ...
- Node.js脚本项目合集(一):Node.js+FFmpeg实现批量从B站导出离线缓存视频到mp4格式,mp4转mp3,实现听歌自由
Node.js脚本项目合集(一):Node.js+FFmpeg实现批量从B站导出离线缓存视频到mp4格式,mp4转mp3,实现听歌自由 前言 一.准备工作以及介绍 1.什么是FFmpeg 2.FFmp ...
- 自己动手写工具:百度图片批量下载器
开篇:在某些场景下,我们想要对百度图片搜出来的东东进行保存,但是一个一个得下载保存不仅耗时而且费劲,有木有一种方法能够简化我们的工作量呢,让我们在离线模式下也能爽爽地浏览大量的美图呢?于是,我们想到了 ...
最新文章
- CSDN蒋涛大数据表明:DCO - 区块链时代企业级服务的全新机会
- Windows删除指定时间之前指定后缀名的文件
- doctype声明、浏览器的标准、怪异等模式
- matlab 特征值不排序,matlap 代码求解释!从这里开始即可%对特征值进行排序并去掉...
- mysql 5.5 特性_MySQL5.5复制新特性
- 2019 Web 前端热点笔试面试题总结(转载)
- 蛙蛙推荐:在c#使用IOCP(完成端口)的简单示例
- 实战篇-六十六行完成简洁的Rss输出类
- 关于整型和浮点型的输出问题
- svpwm的matlab模型,SVPWM的matlab仿真实现
- python 入门教程
- java常量池在哪里_【Java基础】Java常量池在哪里? - 收获啦
- 使用Excel批量生成SQL语句
- Zigbee和WiFi的信道重叠
- 中级计算机软件师考试试题,计算机水平考试-(a)中级软件设计师下午试题模拟64.doc...
- 解决VMware和VMbox实体机和虚拟机无法复制粘贴的问题
- Oracle DBA 转行,作为一名oracle dba需要学习的知识
- 如何实现按键的短按、长按检测?
- SQLSERVER EXPRESS 安装失败 code1645
- 雨听 | 英语学习笔记(六)~作文范文:公务员考试的热潮