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

简介:
复制代码
//======================================================
// abaike图片批量下载Node.js爬虫1.01
// 1.01 修正了输出目录,增加了log.
// 2017年11月11日
//======================================================

// 内置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);        
            var picCount=0;

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

                if(picUrl.indexOf('.jpg')!=-1){
                    pictures.push(picUrl); 
                    picCount++;
                } 
            })   
            console.log("找到图片"+picCount+"张.");
                
            var nextPageUrl=null;
            // 找下一页
            $(".pagelist a").each(function(index,element){
                var text=$(element).text();

                if(text.indexOf('下一页')!=-1){
                    nextPageUrl=$(element).attr("href");
                    console.log("找到下一页.");
                }        
            })

            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();
}

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);
    }
}

function appendToLogfile(folder,text){
    fs.appendFile('./'+folder+'.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://www.avbaike.net/wp-content/uploads/2016/08/108.jpg
//--------------------------------------
function downloadPic(picUrl,folder){
    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="./"+folder+picName;
            fs.writeFile(fileName, imgData, "binary", function(err){
                if(err){
                    console.log("文件"+fileName+"下载失败.");
                    console.log(err);
                    appendToLogfile(folder,"文件"+fileName+"下载失败.\n");
                    failed++;
                }else{
                    console.log("文件"+fileName+"下载成功");
                    succeed++;
                }
            });    
        });
    });

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

    // 出错处理
    req.on('error',function(err){
        if(err.code=="ECONNRESET"){
            console.log('[downloadPic]socket端口连接超时,');
            console.log('导致'+picUrl+"下载失败.");
            console.log(err);
            appendToLogfile(folder,"文件"+picUrl+"下载失败.\n");
        }else{
            console.log('[downloadPic]请求发生错误,err.code:'+err.code);
            console.log('导致'+picUrl+"下载失败.");
            console.log(err);
        }

        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();
复制代码
相关文章
|
16天前
|
JavaScript 前端开发 安全
【逆向】Python 调用 JS 代码实战:使用 pyexecjs 与 Node.js 无缝衔接
本文介绍了如何使用 Python 的轻量级库 `pyexecjs` 调用 JavaScript 代码,并结合 Node.js 实现完整的执行流程。内容涵盖环境搭建、基本使用、常见问题解决方案及爬虫逆向分析中的实战技巧,帮助开发者在 Python 中高效处理 JS 逻辑。
|
4月前
|
前端开发 JavaScript 容器
制作b超单生成器, 假怀孕b超单图片制作, p图医院证明【css+html+js装逼恶搞神器】
本资源提供一个适合用于熟人之间恶搞的工具,效果逼真,仅供学习参考与娱乐。包含前端技术学习要点:语义化布局、响应式设计、Flexbox、图片自适应
|
11月前
|
Web App开发 JavaScript 前端开发
Node.js 是一种基于 Chrome V8 引擎的后端开发技术,以其高效、灵活著称。本文将介绍 Node.js 的基础概念
Node.js 是一种基于 Chrome V8 引擎的后端开发技术,以其高效、灵活著称。本文将介绍 Node.js 的基础概念,包括事件驱动、单线程模型和模块系统;探讨其安装配置、核心模块使用、实战应用如搭建 Web 服务器、文件操作及实时通信;分析项目结构与开发流程,讨论其优势与挑战,并通过案例展示 Node.js 在实际项目中的应用,旨在帮助开发者更好地掌握这一强大工具。
298 1
|
9月前
|
移动开发 JavaScript 前端开发
【Html.js——图片折叠效果】折叠手风琴(蓝桥杯真题-1763)【合集】
本项目实现了一个图片折叠手风琴效果,使用jQuery完成。主要包括以下部分: - **介绍**:任务是通过点击图片实现折叠和展开的效果。 - **准备**:内置初始代码,包含 `css/style.css`、`images/` 文件夹、`js/` 文件夹及 `index.html` 等文件。启动 Web Server 服务可运行项目。 - **目标**:完善 `index.js` 文件,使页面达到预期的折叠效果。 - **规定**:严格按步骤操作,保持默认文件结构不变,并在完成后保持 Web 服务正常访问状态。 - **通关代码**:使用 jQuery 实现点击事件,为选中元素添加 `act
122 19
|
10月前
|
JavaScript 容器
带方向感知功能的js图片遮罩层插件
带方向感知功能的js图片遮罩层插件
|
10月前
|
存储 JavaScript NoSQL
Node.js新作《循序渐进Node.js企业级开发实践》简介
《循序渐进Node.js企业级开发实践》由清华大学出版社出版,基于Node.js 22.3.0编写,包含26个实战案例和43个上机练习,旨在帮助读者从基础到进阶全面掌握Node.js技术,适用于初学者、进阶开发者及全栈工程师。
151 9
|
11月前
|
JSON JavaScript 前端开发
使用JavaScript和Node.js构建简单的RESTful API
使用JavaScript和Node.js构建简单的RESTful API
|
JSON JavaScript 前端开发
JS动态加载以及JavaScript void(0)的爬虫解决方案
Intro 对于使用JS动态加载, 或者将下一页地址隐藏为JavaScript void(0)的网站, 如何爬取我们要的信息呢? 本文以Chrome浏览器为工具, 36Kr为示例网站, 使用 Json Handle 作为辅助信息解析工具, 演示如何抓取此类网站.
6802 0
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp的客户关系管理系统附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp的客户关系管理系统附带文章源码部署视频讲解等
243 2

热门文章

最新文章