Node.js aitaotu图片批量下载Node.js爬虫1.00版
即使是https网页,解析的方式也不是一致的,需要多试试。
代码:
//======================================================
// aitaotu图片批量下载Node.js爬虫1.00
// 2017年11月14日
//======================================================
// 内置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.aitaotu.com/rihan/30598.html
// pageUrl sample:https://www.aitaotu.com/rihan/33405.html
//--------------------------------------
function crawl(pageUrl){
console.log("Current page="+pageUrl);
// 得到hostname和path
var 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;
// 找图片放入数组
$("#big-pic p 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;
// 找下一页
$(".pages ul li a").each(function(index,element){
var text=$(element).text();
if(text.indexOf('下一页')!=-1){
nextPageUrl=$(element).attr("href");
nextPageUrl="https://www.aitaotu.com/"+nextPageUrl;// 把省略部分加上
console.log("找到下一页.");
}
})
if(nextPageUrl==null){
console.log(pageUrl+"已经是最后一页了.");
download(pictures);
}else{
//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();
}
var total=0;
var succeed=0;
var failed=0;
//--------------------------------------
// 下载图片
//--------------------------------------
function download(pictures){
var folder='pictures('+getNowFormatDate()+")";
// 创建目录
fs.mkdir('./'+folder,function(err){
if(err){
console.log("目录"+folder+"已经存在");
}
});
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://img.aitaotu.cc:8089/Pics/2017/0410/03/01.jpg
//--------------------------------------
function downloadPic(picUrl,folder){
console.log("图片:"+picUrl+"下载开始");
// 得到hostname,path和port
var currUrl=picUrl.replace("https://","");
var pos=currUrl.indexOf("/");
var hostname=currUrl.slice(0,pos);
var path=currUrl.slice(pos);
var arr=hostname.split(":");
hostname=arr[0];
var 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',
};
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");
failed++;
}else{
appendToLogfile(folder,"文件 "+picUrl+" 下载成功.\n");
console.log("文件"+fileName+"下载成功");
succeed++;
}
});
});
});
// 超时处理
req.setTimeout(7500,function(){
req.abort();
});
// 出错处理
req.on('error',function(err){
if(err){
console.log('[downloadPic]文件'+picUrl+"下载失败,"+'因为'+err);
appendToLogfile(folder,"文件"+picUrl+"下载失败.\n");
}
failed++;
});
// 请求结束
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月14日18:28:37
Node.js aitaotu图片批量下载Node.js爬虫1.00版的更多相关文章
- Node.js umei图片批量下载Node.js爬虫1.00
这个爬虫在abaike爬虫的基础上改改图片路径和下一页路径就出来了,代码如下: //====================================================== // ...
- Node.js abaike图片批量下载Node.js爬虫1.01版
//====================================================== // abaike图片批量下载Node.js爬虫1.01 // 1.01 修正了输出目 ...
- Node.js abaike图片批量下载Node.js爬虫1.00版
这个与前作的差别在于地址的不规律性,需要找到下一页的地址再爬过去找. //====================================================== // abaik ...
- Node.js mimimn图片批量下载爬虫 1.00
这个爬虫在Referer设置上和其它爬虫相比有特殊性.代码: //====================================================== // mimimn图片批 ...
- Node.js nvshens图片批量下载爬虫 1.00
//====================================================== // www.nvshens.com图片批量下载Node.js爬虫1.00 // 此程 ...
- Node.js meitulu图片批量下载爬虫1.06版
//====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1. ...
- Node.js meitulu图片批量下载爬虫 1.05版(Final最终版)
//====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1. ...
- Node.js meitulu图片批量下载爬虫1.04版
//====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1. ...
- Node.js meitulu图片批量下载爬虫1.03版
//====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1. ...
随机推荐
- vue2.0项目结构和打包发布
先来一张项目结构图: 本地开发测试运行的命令是npm run dev 打包发布的命令是 npm run build生成的dist文件夹里的文件就是我们可以布置到服务上的文件 但是呢,这打包好的文件的文 ...
- centos7.5&ubuntu18.10安装Google浏览器
一.手动安装 1. 下载 rpm 包https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm 2. 安装依赖 ...
- SpringMVC一些功能
1.日期格式转换 当页面提交日期格式时 默认的格式为2017/10/1 如果指定日期格式为2017-10-1 //初始化绑定日期格式--不定义初始化格式时只能默认用yyyy/MM/dd格式 @Init ...
- ubuntu要安装新软件,已有deb安装包
如果ubuntu要安装新软件,已有deb安装包(例如:iptux.deb),但是无法登录到桌面环境.那该怎么安装?答案是:使用dpkg命令.dpkg命令常用格式如下:sudo dpkg -I iptu ...
- 【PHPExcel实例】 php 导出 excel 实例
CREATE TABLE `person` ( `) DEFAULT NULL, `name` ) DEFAULT NULL, `birthday` date DEFAULT NULL ) ENGIN ...
- Python3 文件读写注意事项(指针问题)
C:\Users\Administrator\AppData\Local\Programs\Python\Python35\python.exe E:/python/day2/op.py Someho ...
- 解决CDH的web界面使用nginx代理一些静态文件无法加载
vim /opt/cm-/share/cmf/webapp/WEB-INF/spring/mvc-config.xml .... 注释此行 <bean class="com.cloud ...
- 第2天:Ansible-Inventory管理
在Ansible中,将可管理的服务器集合成为Inventory.因此,Inventory管理便是服务器管理. hosts文件位置 我们知道,Ansible在执行操作时,首先需要确定对哪些服务器执行操作 ...
- UGUI的优点新UI系统三效率高效果好
UGUI的优点新UI系统三效率高效果好 通过对批处理(batching).纹理图集(texture atlasing)和新的canvas组件的支持,新UI系统提供了一个经过优化的解决方案,使得开发者添 ...
- 【并查集】Gym - 101128B - Black Vienna
有26张牌(A~Z),其中三张被拿走了.其余23张被分发给了两个人.给你m次调查结果,一次调查结果是对其中一个人询问一对牌,他会告诉你他有这对牌的几张(0~2).问你有多少种被拿走的牌的组合. 三重循 ...