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 ...
随机推荐
- 8种json数据查询方式
你有没有对“在复杂的JSON数据结构中查找匹配内容”而烦恼.这里有8种不同的方式可以做到: JsonSQL JsonSQL实现了使用SQL select语句在json数据结构中查询的功能. 例子: ? ...
- MediaPlayer滑动不准的问题
因为MediaPlayer在seekto是异步进行的,如果在滑动过程中暂停,会导致滑动不准确的情况,这时候就需要添加滑动完成的监听即setOnSeekCompleteListener
- 17-7-24-react入门
先说明下为什么说好每天一更,周五周六周日都没有更新.因为在周五的时候,上司主动找我谈了转正后的工资4-4.5K.本来想好是6K的,后来打听了一圈公司的小伙伴,都是5-5.5,我就把自己定到了5K.万万 ...
- Java实现蛇形矩阵
public class Solution { //下x++ 左y-- 上x-- 右y++ public void prints(int n) { int[][] mp = new int[n][n] ...
- Pandas分组运算(groupby)修炼
Pandas分组运算(groupby)修炼 Pandas的groupby()功能很强大,用好了可以方便的解决很多问题,在数据处理以及日常工作中经常能施展拳脚. 今天,我们一起来领略下groupby() ...
- 【vim】mac配置vim,molokai配色
效果如下: 首先修改主目录下的.vimrc: "======================================================================= ...
- UVA 147(子集和问题)
Dollars New Zealand currency consists of $100, $50, $20, $10, and $5 notes and $2, $1, 50c, 20c, 10 ...
- webpack2 热加载js 文件
如果只要普通的热加载 只要如下配置就好了 package.json { "devDependencies": { "webpack": "^2.6.1 ...
- EasyUI学习总结(一)——EasyUI入门(转载)
本文转载自:http://www.cnblogs.com/xdp-gacl/p/4075079.html 一.EasyUI下载 EasyUI官方下载地址:http://www.jeasyui.com/ ...
- Gauss 消元(模板)
/* title:Gauss消元整数解/小数解整数矩阵模板 author:lhk time: 2016.9.11 没学vim的菜鸡自己手打了 */ #include<cstdio> #in ...