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

//======================================================
// abaike图片批量下载Node.js爬虫1.00
// 2017年11月9日
//======================================================

// 内置http模块
var http=require("http");

// 内置文件处理模块,用于创建目录和图片文件
var fs=require('fs');

// cheerio模块,提供了类似jQuery的功能,用于从HTML code中查找图片地址和下一页
var cheerio = require("cheerio");

// 请求参数JSON。http和https都有使用
var options;

// request请求
var req;

// 图片数组,找到的图片地址会放到这里
var pictures=[];

//--------------------------------------
// 爬取网页,找图片地址,再爬
// pageUrl sample:http://www.avbaike.net/27812.html
// pageUrl sample:http://www.avbaike.net/27812.html/2
//--------------------------------------
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){
        resp.setEncoding('utf8');
        var body="";

        resp.on('data',function(chunk){
            body+=chunk;
        });

        resp.on('end',function(){
            //console.log("body="+body);
            var $ = cheerio.load(body);            

            // 找图片放入数组
            $("#post_content p a").each(function(index,element){
                var picUrl=$(element).attr("href");
                //console.log(picUrl);
                pictures.push(picUrl);
            })   

            var nextPageUrl=null;
            // 找下一页
            $(".pagelist a").each(function(index,element){
                var text=$(element).text();
                if(text.indexOf('下一页')!=-1){
                    nextPageUrl=$(element).attr("href");
                }
            })

            if(nextPageUrl==null){
                console.log(pageUrl+"已经是最后一页了.");
                download(pictures);
            }else{
                //console.log("下一页是"+nextPageUrl);
                crawl(nextPageUrl);
            }
        });
    });

    // 超时处理
    req.setTimeout(10000,function(){
        req.abort();
    });

    // 出错处理
    req.on('error',function(err){
        if(err.code=="ECONNRESET"){
            console.log('[crawl]socket端口连接超时。');
            console.log(err);
        }else{
            console.log('请求发生错误,err.code:'+err.code);
        }
    });

    // 请求结束
    req.end();
}

//--------------------------------------
// 下载图片
//--------------------------------------
function download(pictures){
    var folder='pictures';
    // 创建目录
    fs.mkdir('./'+folder,function(err){
        if(err){
            console.log("目录"+folder+"已经存在");
        }
    });

    console.log("总计有"+pictures.length+"张图片将被下载.");
    for(var i=0;i<pictures.length;i++){
        var picUrl=pictures[i];
        downloadPic(picUrl);
    }
}

//--------------------------------------
// 下载单张图片
// picUrl sample:http://www.avbaike.net/wp-content/uploads/2016/08/108.jpg
//--------------------------------------
function downloadPic(picUrl){
    console.log("图片:"+picUrl+"下载开始");

    // 得到hostname和path
    var currUrl=picUrl.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);

    var picName=currUrl.slice(currUrl.lastIndexOf("/"));

    // 初始化options
    options={
        hostname:hostname,
            port:80,
            path:path,// 子路径
          method:'GET',
    };

    req=http.request(options,function(resp){
        var imgData = "";
        resp.setEncoding("binary"); 

        resp.on('data',function(chunk){
            imgData+=chunk;
        });

        resp.on('end',function(){        

            // 创建文件
            var fileName="./pictures"+picName;
            fs.writeFile(fileName, imgData, "binary", function(err){
                if(err){
                    console.log("文件"+fileName+"下载失败.");
                    console.log(err);
                }else{
                    console.log("文件"+fileName+"下载成功");
                }
            });
        });
    });

    // 超时处理
    req.setTimeout(10000,function(){
        req.abort();
    });

    // 出错处理
    req.on('error',function(err){
        if(err.code=="ECONNRESET"){
            console.log('[downloadPic]socket端口连接超时。');
            console.log(err);
        }else{
            console.log('[downloadPic]请求发生错误,err.code:'+err.code);
            console.log(err);
        }
    });

    // 请求结束
    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();

Node.js abaike图片批量下载Node.js爬虫1.00版的更多相关文章

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

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

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

    //====================================================== // abaike图片批量下载爬虫1.02 // 用最近的断点续传框架改写原有1.01 ...

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

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

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

    即使是https网页,解析的方式也不是一致的,需要多试试. 代码: //====================================================== // aitaot ...

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

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

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

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

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

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

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

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

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

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

随机推荐

  1. 【bzoj3924&&luogu3345】幻想乡战略游戏

    这题可以用线段树做,不过正解恐怕是动态点分治?(点分树) 简单介绍下动态点分治的概念:在点分治的过程中,一般我们面对的问题都是静态的.如果涉及到修改这类的操作,我们就希望找到我们是如何处理到当前的修改 ...

  2. [BZOJ1491][NOI2007]社交网络 floyd

    1491: [NOI2007]社交网络 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 2196  Solved: 1170[Submit][Status ...

  3. iOS运行时,如何增加成员变量

    必须实现getter和setter方法 ``` - (void)setName:(NSString *)name { /** * 为某个类关联某个对象 * * @param object#> 要 ...

  4. php 单文件上传

    php 单文件上传 通过 PHP,可以把文件上传到服务器. 创建一个文件上传表单 允许用户从表单上传文件是非常有用的. 请看下面这个供上传文件的 HTML 表单: Filename: 请留意如下有关此 ...

  5. 【转】持续集成 Sonar 平台搭建及 Sonar 自定义规则打包部署篇

    引言 基于阿里开发手册的sonar自定义插件工程 开源地址: https://github.com/tigerge000/sonar-java-custom-rules.git由于最近来问童鞋,就算写 ...

  6. codeforces 869C The Intriguing Obsession【组合数学+dp+第二类斯特林公式】

    C. The Intriguing Obsession time limit per test 1 second memory limit per test 256 megabytes input s ...

  7. 1953 Problem B #103. 子串查找

    #include<stdio.h> #include<string.h> main() { char a[100],b[100]; int n,k,i; gets(a); ge ...

  8. MapReduce 编程模板

    1.MapReduce 编程模型的5个步骤: 1)迭代,将输入数据解析成 key/value 对: 2)将解析的 key/value经过Map处理映射成另一组key/value对: 3)根据key进行 ...

  9. 基于JS的event-manage事件管理库(一步一步实现)

    关于文章 最近在提升个人技能的同时,决定把自己为数不多的沉淀记录下来,让自己理解的更加深刻,同时也欢迎各位看官指出不足之处. 随着node.js的盛行,引领着Javascript上天下地无所不能啊,本 ...

  10. TDD开发案例

    前段时间把一个界面框架完成了,今天基于这个框架开发一个小模块,在这里把这个模块设计的全过程记录下来,希望大家讨论并指正. 一.起因 公司交给我一个任务,为测试员写一个手机模拟界面,以方便她们的手机短信 ...