【Python】【Nodejs】下载单张图片到本地,Python和Nodejs的比较

2023-07-29,,

Python版本:

# 下载单张图片到本地,看用时多少
import urllib.request
import datetime

starttime = datetime.datetime.now()
pic='https://img.onvshen.com:85/gallery/23789/22210/s/0.jpg'

name=pic.split('/')[-1]

rsp=urllib.request.urlopen(pic)
img=rsp.read()
with open(name,'wb') as f:
    f.write(img)
print('图片'+pic+'下载完成')

endtime = datetime.datetime.now()
print("下载用时"+str((endtime - starttime).seconds)+"秒")

Nodejs版本:

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

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

function downloadPic(picUrl){
    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);

    // 有端口加端口,没有端口默认80
    var port=85;
    if(hostname.indexOf(":")!=-1){
        var arr=hostname.split(":");
        hostname=arr[0];
        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',
        /* headers:{
            'Referer':'https://www.nvshens.com',
          },*/  // 有需要再打开
    };

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

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

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

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

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

    // 出错处理
    req.on('error',function(err){
        if(err){
            console.log('[downloadPic]文件   '+picUrl+"  下载失败,"+'因为'+err);
            appendToLogfile(folder,"文件"+picUrl+"下载失败.\n");
        }
    });

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

console.time("共花费了");
downloadPic('https://img.onvshen.com:85/gallery/23789/22210/s/0.jpg')
console.timeEnd("共花费了"); 

感觉Nodejs的更快些,可能是Python在判断下载模式上花费了时间。

【Python】【Nodejs】下载单张图片到本地,Python和Nodejs的比较的相关教程结束。

《【Python】【Nodejs】下载单张图片到本地,Python和Nodejs的比较.doc》

下载本文的Word格式文档,以方便收藏与打印。