【Python】【Nodejs】下载单张图片到本地,Python和Nodejs的比较
2024-09-01 18:01:16
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在判断下载模式上花费了时间。
最新文章
- ps命令
- EntityFramework 7 Linq Contains In 奇怪问题
- YUM仓库服务
- CentOS(RedHat)命令行永久修改IP地址、网关、DNS
- VisualSVN Server搭建VDFS分布式仓研究(未成功)
- linux下安装mysql数据库与相关操作
- delphi 修改Hint的字体和颜色
- UVa 294 (因数的个数) Divisors
- TimePicker 和TimePickerDiag
- spring+springmvc+maven+mybatis整合
- linux下的vim使用笔记
- C语言--总结报告
- Spark的四种部署方式并对应四种提交方式
- this 相关(2)
- NYOJ 85:有趣的数(打表,规律)
- SEO工作中如何增加用户体验?10个细节要注意!
- 《剑指offer》第八题(重要!查找二叉树的中序遍历的下一个结点)
- linq中当生成asp.net实体模式时
- 《Linux内核与分析》第六周
- MySQL查看和修改wait_timeout
热门文章
- Sublime 编译运行JavaScript
- 批量 修改 android eclipse 项目名
- [CODE FESTIVAL 2018]Sushi Restaurant
- bzoj 3223 文艺平衡树 Splay 打标志
- 为什么java的构造方法中this()或者super()要放在第一行
- python开发_random
- [转]Intent和IntentFilter详解
- 使用pyplot和seaborn进行画图
- Java集合--HashMap分析
- ExtJS4.1 ExtJS TabPanel 双击标签关闭该页