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

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

//======================================================
// 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();
时间: 2024-08-03 07:52:46

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

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

即使是https网页,解析的方式也不是一致的,需要多试试. 代码: //====================================================== // aitaotu图片批量下载Node.js爬虫1.00 // 2017年11月14日 //====================================================== // 内置http模块 var https=require("https"); // 内置文件处理模块,

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

在 http://www.cnblogs.com/xiandedanteng/p/7614051.html 一文我曾经书写过一个图片下载爬虫,但原有程序不是为下载图片而设计故有些绕,于是稍微改写了一下,可读性应该稍好些.功能上和原程序差不多,只是输出目录不是固定在test目录了.代码如下: //================================================ // https://www.meitulu.com图片批量下载Node.js爬虫1.01 // 2017

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

//====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1.06 // 1.00 完成图片爬虫,手动输入页数和目录 // 1.01 改写. // 1.02 手动输入页面url,然后自动解析 // 1.03 从命令行获得页面url,然后自动解析 // 1.04 解决数量节点位置不固定bug和输入状态不退出bug // 1.05 增加自动模式和手动模式 // 1

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

//====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1.03 // 1.01 手动输入页数和目录 // 1.02 手动输入页面url,然后自动解析 // 1.02 从命令行获得页面url,然后自动解析 // 2017年11月6日 //====================================================== // 内置h

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

//====================================================== // www.nvshens.com图片批量下载Node.js爬虫1.00 // 此程序与meitulu爬虫类似,先写个架子在这里 // 2017年11月9日 //====================================================== // 内置https模块 var https=require("https"); // 内置文件处理模

Node.js mm131图片批量下载爬虫1.01 增加断点续传功能

这里的断点续传不是文件下载时的断点续传,而是指在爬行页面时有时会遇到各种网络中断而从中断前的页面及其数据继续爬行的过程,这个过程和断点续传原理上相似故以此命名. 代码如下: //====================================================== // mm131图片批量下载爬虫1.01 // 1.00 具备功能 // 1.01 增加断点续传 // 2017年11月15日 //========================================

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

这个爬虫依然需要iconv转码,想不到如今非utf8的网页还这么多.另外此网页找下一页的方式比较异常,又再次借助了正则表达式. 代码如下: //====================================================== // 4493图片批量下载爬虫1.00 // 2017年11月19日 //====================================================== // 内置https模块 var https=require(

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

//====================================================== // nvshens图片批量下载爬虫1.01 // 用最近的断点续传框架改写原有1.00版程序 // 2017年11月21日 //====================================================== // 内置https模块 var https=require("https"); // 内置http模块 var http=requir

&lt;&lt;&lt; JS实现网页批量下载文件,支持PC/手机

//把下载链接放入集合里 var downloadData = new Array{"http://www.empli.com/data1.apk","http://www.empli.com/data1.apk","http://www.empli.com/data1.apk","http://www.empli.com/data1.apk"}; var downloadNum=0;//方法执行次数 circularWind