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 ...
随机推荐
- 开源IDS系列--【2015】获取snort vrt 规则(talo)
1.在snort网站注册 2.注册成功后,会在个人信息中生成:Oinkcode 3.https://www.snort.org/rules/snortrules-snapshot-2973.tar.g ...
- vue-music 关于Search(搜索页面)--上拉加载
建立搜索框组件页面,searchBox,组件接受一个可以自定义传入的placeholder 属性.input v-model 双向绑定数据关联到query 中, 在created中监听 quer ...
- Java工具类-格式化日期
package common; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; p ...
- 洛谷—— P2562 [AHOI2002]Kitty猫基因编码
P2562 [AHOI2002]Kitty猫基因编码 题目描述 小可可选修了基础生物基因学.教授告诉大家 Super Samuel 星球上 Kitty猫的基因的长度都是 2 的正整数次幂 ), 全是由 ...
- Visual Studio 2017启动x86的Android模拟器失败
Visual Studio 2017启动x86的Android模拟器失败 Visual Studio 2017默认提供多个Android模拟器.其中,x86模拟器运行较快.但是由于和Hyper-V服 ...
- angularjs学习笔记3-directive中scope的绑定修饰符
在angularjs中,一个directive返回一个对象,对象存在很多属性,并且可以在directive中自定义自己的scope,而使用自己的scope是为了防止一个directive被使用在多个地 ...
- ServletContext (上下文对象)
一.什么是ServletContext ServletContext代表是一个web应用的上下文对象(web应用对象) 里面封装的都是web应用信息 一个ServletContext对应一个应用 二. ...
- Codeforces 455 B. A Lot of Games
\(>Codeforces \space 455 B. A Lot of Games<\) 题目大意 : 有两个人在玩游戏,一共玩 \(k\) 轮,每一轮的一开始有一个空串,双方每一回合需 ...
- FZU 2105 Digits Count(按位维护线段树)
[题目链接] http://acm.fzu.edu.cn/problem.php?pid=2105 [题目大意] 给出一个序列,数字均小于16,为正数,每次区间操作可以使得 1. [l,r]区间and ...
- 【模拟退火】poj2069 Super Star
题意:让你求空间内n个点的最小覆盖球. 模拟退火随机走的时候主要有这几种走法:①随机旋转角度. ②直接不随机,往最远的点的方向走,仅仅在尝试接受解的时候用概率.(最小圆/球覆盖时常用) ③往所有点的方 ...