使用模块线程方式实现网络资源的下载。
业务要求:
- 确定网络资源的下载地址
- 显示下载文件的相关信息
- 下载实时显示下载百分比
- 实现多个任务同时下载
运行参考截图:
技术需求:
使用Urllib模块实现
使用sys.stdout( ) 函数定点输出信息(进度百分比实时显示)
使用urllib.request.urlretrieve( ) 函数获取远程资源大小并实现下载保存
下载功能需要在线程中运行处理
程序如下:
import threading import urllib.request,urllib.response import os import sys #创建一个线程类 class DownLoadThread(threading.Thread): def __init__(self,url,savePath,fileName): threading.Thread.__init__(self) self.__url=url self.__savePath=savePath self.__fileName=fileName pass def run(self): ''' @name:schedule @args:int,int,int @return:none @data:2019.8.14 ''' def schedule(block, blocksize, contentLength): '计算并显示下载速度' #block:已经下载的数据块大小 #blocksize:数据块大小 #contentLength:远程文件大小 #计算下载百分比 per = 100.0 * block * blocksize / contentLength if per > 100: per = 10 #在同一位置输出数据 sys.stdout.write('Download progress:%d%% \r' % (per)) sys.stdout.flush() pass os.system('cls') #输出数据 print('下载文件的基本信息:') print('_'*30) print('文件名称:{0}'.format(self.__fileName)) fileType = self.__fileName.split('.')[-1] print('文件类型:{0}'.format(fileType)) #计算远程文件大小 #使用urllib.request.urlretrieve()函数获取headers信息 local_filename,headers=urllib.request.urlretrieve(self.__url) #获取文件大小值 contentLength = int(headers['Content-Length']) print('文件大小:{0}'.format(contentLength)) print('下载地址:{0}'.format(self.__url)) print('保存路径:{0}'.format(self.__savePath)) print('_'*30) print('[启动]>>> {0}文件启动下载....'.format(self.__fileName)) #试用期urlretrieve(资源地址,保存路径,过程回调)函数实现文件下载 urllib.request.urlretrieve(self.__url,self.__savePath, schedule) print('DownLoad progress:100%') print('[完成]>>> {0}文件下载完毕.'.format(self.__fileName)) pass pass #脚本入口 if __name__ =='__main__': #获取远程文件的基本数据 #设置网络地址 url='https://s.ssl.qhimg.com/static/61bc8925b74cf513.js' fileName = url.split('/')[-1] #设置下载保存路径 savaPath = os.path.join(os.getcwd(),'D:\Python\demo\day16'+fileName) #创建下载线程 downloadthread = DownLoadThread(url,savaPath,fileName) #启动下载线程 downloadthread.start() downloadthread.join()