Node.js mm131图片批量下载爬虫1.00 iconv协助转码
//====================================================== // mm131图片批量下载爬虫1.00 // 2017年11月15日 //====================================================== // 内置http模块 var http=require("http"); // 内置文件处理模块,用于创建目录和图片文件 var fs=require('fs'); // 用于转码。非Utf8的网页如gb2132会有乱码问题,需要iconv将其转码 var iconv = require('iconv-lite'); // cheerio模块,提供了类似jQuery的功能,用于从HTML code中查找图片地址和下一页 var cheerio = require("cheerio"); // 请求参数JSON。http和https都有使用 var options; // request请求 var req; // 图片数组,找到的图片地址会放到这里 var pictures=[]; //-------------------------------------- // 爬取网页,找图片地址,再爬 // pageUrl sample:http://www.mm131.com/xinggan/2852.html // pageUrl sample:http://www.mm131.com/xinggan/2853.html // pageUrl sample:http://www.mm131.com/xinggan/2976.html //-------------------------------------- function crawl(pageUrl){ console.log("Current page="+pageUrl); // 得到hostname和path var currUrl=pageUrl.replace("http://",""); 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:80, path:path,// 子路径 method:'GET', }; req=http.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 = iconv.decode(buffer,'gb2312'); // 特地增加的,为了让汉字不乱码,header里面有<meta http-equiv="Content-Type" content="text/html; charset=gb2312">字样都需要iconv帮忙转码 //console.log(body); var $ = cheerio.load(body); var picCount=0; // 找图片放入数组 $(".content-pic 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 nextPageUrl=null; // 找下一页 $(".content-page a").each(function(index,element){ var text=$(element).text(); if(text.indexOf('下一页')!=-1){ nextPageUrl=$(element).attr("href"); nextPageUrl="http://www.mm131.com/xinggan/"+nextPageUrl;// 把省略部分加上 console.log("找到下一页."); } }) if(nextPageUrl==null){ console.log(pageUrl+"已经是最后一页了.\n"); download(pictures); }else{ //console.log("下一页是"+nextPageUrl); crawl(nextPageUrl); } }).on("error", function() { console.log("获取失败") }) }); // 超时处理 req.setTimeout(7500,function(){ req.abort(); }); // 出错处理 req.on('error',function(err){ console.log('请求发生错误'+err); }); // 请求结束 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:http://img2.mm131.com:55888/pic/2852/1.jpg //-------------------------------------- function downloadPic(picUrl,folder){ console.log("图片:"+picUrl+"下载开始"); // 得到hostname,path和port var currUrl=picUrl.replace("http://",""); var pos=currUrl.indexOf("/"); var hostname=currUrl.slice(0,pos); var path=currUrl.slice(pos); // 有端口加端口,没有端口默认80 var port=80; if(hostname.indexOf(":")!=-1){ var arr=hostname.split(":"); hostname=arr[0]; port=arr[1]; } //console.log("hostname="+hostname); //console.log("path="+path); //console.log("port="+port); var picName=currUrl.slice(currUrl.lastIndexOf("/")); // 初始化options options={ hostname:hostname, port:port, path:path,// 子路径 method:'GET', headers:{ 'Referer':'http://www.mm131.com', } }; req=http.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();
2017年11月15日20:54:16
Node.js mm131图片批量下载爬虫1.00 iconv协助转码的更多相关文章
- Node.js mm131图片批量下载爬虫1.01 增加断点续传功能
这里的断点续传不是文件下载时的断点续传,而是指在爬行页面时有时会遇到各种网络中断而从中断前的页面及其数据继续爬行的过程,这个过程和断点续传原理上相似故以此命名.我的具体做法是:在下载出现故障或是图片已 ...
- Node.js mzitu图片批量下载爬虫1.00
又攻下一座山头. //====================================================== // mzitu图片批量下载爬虫1.00 // 2017年11月19 ...
- Node.js 4493图片批量下载爬虫1.00
这个爬虫依然需要iconv转码,想不到如今非utf8的网页还这么多.另外此网页找下一页的方式比较异常,又再次借助了正则表达式. 代码如下: //============================ ...
- Node.js monly图片批量下载爬虫1.00
此爬虫又用到了iconv转码,代码如下: //====================================================== // mmonly图片批量下载爬虫1.00 ...
- Node.js m03122图片批量下载爬虫1.00
//====================================================== // m03122图片批量下载爬虫1.00 // 2017年11月18日 //==== ...
- Node.js mimimn图片批量下载爬虫 1.00
这个爬虫在Referer设置上和其它爬虫相比有特殊性.代码: //====================================================== // mimimn图片批 ...
- Node.js nvshens图片批量下载爬虫 1.00
//====================================================== // www.nvshens.com图片批量下载Node.js爬虫1.00 // 此程 ...
- Node.js abaike图片批量下载爬虫1.02
//====================================================== // abaike图片批量下载爬虫1.02 // 用最近的断点续传框架改写原有1.01 ...
- Node.js nvshens图片批量下载爬虫1.01
//====================================================== // nvshens图片批量下载爬虫1.01 // 用最近的断点续传框架改写原有1.0 ...
随机推荐
- 通过javascript进行UTF-8编码
通过javascript进行UTF-8编码 javascript的字符集: javascript程序是使用Unicode字符集编写的.Unicode是ASCII和Latin-1的超集,并支持地球上几乎 ...
- gulp在webstorm里运行,告别cmd控制台!
使用webstorm运行gulp程序,不再用一直开着cmd了!鬼知道自己会不会不小心关闭了cmd呢.看截图操作吧! 如果你的gulp设置了default任务,那么直接点击“运行‘default‘’就行 ...
- Web测试中容易被忽略的Charset问题
今天继续进行一个更综合的脚本制作,录制设置.进行录制.脚本修改,一切都轻车熟路,进行得很顺利.经过近一个小时的对比和修改,OK,脚本大功告成,终于可以小试牛刀了,嘿嘿. 运行,replay lo ...
- 四十四 常用内建模块 struct
准确地讲,Python没有专门处理字节的数据类型.但由于str既是字符串,又可以表示字节,所以,字节数组=str.而在C语言中,我们可以很方便地用struct.union来处理字节,以及字节和int, ...
- coercing to Unicode错误的一个解决办法
http://blog.csdn.net/happen23/article/details/46683813
- scrapy抓取拉勾网职位信息(二)——拉勾网页面分析
网站结构分析: 四个大标签:首页.公司.校园.言职 我们最终是要得到详情页的信息,但是从首页的很多链接都能进入到一个详情页,我们需要对这些标签一个个分析,分析出哪些链接我们需要跟进. 首先是四个大标签 ...
- c++风格
http://web.archive.org/web/20160430022340/http://google.github.io/styleguide/cppguide.html 主要注意几点: 函 ...
- 1、编译安装Nginx
1.1 如何选择web服务器 在实际工作中,我们需要根据业务需求来选择合适的业务服务软件,有关web服务,选择建议如下: 静态业务:若是高并发场景,尽量采用nginx或lighttpd,二者首选ngi ...
- 【kubernetes】ubuntu14.04 64位 搭建kubernetes过程
背景: Kubernetes介绍:http://kubernetes.io/docs/getting-started-guides/ github地址:https://github.com/kuber ...
- Failure INSTALL FAILED DUPLICATE PERMISSION
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha Failure [INSTALL_FAILED_DUPLICATE_PERMISSION ...