即使是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版的更多相关文章

  1. Node.js umei图片批量下载Node.js爬虫1.00

    这个爬虫在abaike爬虫的基础上改改图片路径和下一页路径就出来了,代码如下: //====================================================== // ...

  2. Node.js abaike图片批量下载Node.js爬虫1.01版

    //====================================================== // abaike图片批量下载Node.js爬虫1.01 // 1.01 修正了输出目 ...

  3. Node.js abaike图片批量下载Node.js爬虫1.00版

    这个与前作的差别在于地址的不规律性,需要找到下一页的地址再爬过去找. //====================================================== // abaik ...

  4. Node.js mimimn图片批量下载爬虫 1.00

    这个爬虫在Referer设置上和其它爬虫相比有特殊性.代码: //====================================================== // mimimn图片批 ...

  5. Node.js nvshens图片批量下载爬虫 1.00

    //====================================================== // www.nvshens.com图片批量下载Node.js爬虫1.00 // 此程 ...

  6. Node.js meitulu图片批量下载爬虫1.06版

    //====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1. ...

  7. Node.js meitulu图片批量下载爬虫 1.05版(Final最终版)

    //====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1. ...

  8. Node.js meitulu图片批量下载爬虫1.04版

    //====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1. ...

  9. Node.js meitulu图片批量下载爬虫1.03版

    //====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1. ...

随机推荐

  1. jQuery插件开发,jquery插件

    关于jQuery插件的开发自己也做了少许研究,自己也写过多个插件,在自己的团队了也分享过一次关于插件的课.开始的时候整觉的很复杂的代码,现在再次看的时候就清晰了许多.这里我把我自己总结出来的东西分享出 ...

  2. Ubuntu下各种环境变量设置

    1.用户目录下的 .bashrc 文件在用户主目录下,有一个 .bashrc 文件,编辑该文件:$gedit ~/.bashrc 在最后边加入需要设置变量的shell语句,例如:export PATH ...

  3. python多线程编程(6): 队列同步

    原文请看:http://www.cnblogs.com/holbrook/archive/2012/03/15/2398060.html 前面介绍了互斥锁和条件变量解决线程间的同步问题,并使用条件变量 ...

  4. html不识别<br/>,后台返回<br/>,前端不换行解决办法

    今天编写页面,后台直接返回带有html格式的字符串,包含<br/>,前端以为要展示<br/>,将其解析为<br/>页面不换行 解决办法 后台将<br/> ...

  5. Why Did the Cow Cross the Road III(树状数组)

    Why Did the Cow Cross the Road III 时间限制: 1 Sec  内存限制: 128 MB提交: 65  解决: 28[提交][状态][讨论版] 题目描述 The lay ...

  6. 树形dp(poj 1947 Rebuilding Roads )

    题意: 有n个点组成一棵树,问至少要删除多少条边才能获得一棵有p个结点的子树? 思路: 设dp[i][k]为以i为根,生成节点数为k的子树,所需剪掉的边数. dp[i][1] = total(i.so ...

  7. Knockout.js(一):简介

    Knockout是一款很优秀的JavaScript库,通过应用MVVM模式使JavaScript前端UI简单化.任何时候你的局部UI内容需要自动更新,KO都可以很简单的帮你实现,并且非常易于维护. K ...

  8. js实现table导出为Excel文件

    1.首先创建好表格. 2.然后在js中写三个方法 1)判断浏览器 2)定义文档类型 template : 定义文档的类型,相当于html页面中顶部的<!DOCTYPE> 声明.(个人理解, ...

  9. 【BZOJ 1815】【SHOI 2006】color 有色图

    http://www.lydsy.com/JudgeOnline/problem.php?id=1815 这道题好难啊,组合数学什么根本不会啊qwq 题解详见08年的Pólya计数论文. 主要思想是只 ...

  10. [BZOJ4025]二分图(线段树分治,并查集)

    4025: 二分图 Time Limit: 20 Sec  Memory Limit: 512 MBSubmit: 2191  Solved: 800[Submit][Status][Discuss] ...