使用requests进行文件下载
def downFile():
url="http://pic.sc.chinaz.com/files/pic/pic9/202005/apic25274.jpg"
res = requests.get(url,stream=True)
filesize=0
if 'Content-Length' in res.headers.keys():
filesize= res.headers['Content-Length']
print('Content-Disposition' in res.headers.keys())
if 'Content-Disposition' in res.headers.keys():
filename=res.headers['Content-Disposition']
searchObj = re.search(r'filename=(.*)', filename, re.M | re.I)
if searchObj:
filename = parse.unquote(searchObj.group(1))
else:
filename=url[url.rfind("/")+1:]
print("下载文件基本信息:")
print('-' * 30)
if filename:
print("文件名称:", filename)
f = open("html/"+filename, "wb")
chunk_size = 512
times = int(filesize) // chunk_size
if filesize > 0:
times = int(filesize) // chunk_size
show = 1 / times
show2 = 1 / times
start = 1
for chunk in res.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
if filesize > 0:
if start <= times:
stdout.write(f"下载进度: {show:.2%}\r")
start += 1
show += show2
else:
stdout.write("下载进度: 100%")
print("\n结束下载")
项目目录结构
关于requests.get(url,stream=True),stream为Flase立即下载,大文件读取出来分段下载
这个是源码对此参数的解释:param stream: (optional) if False
, the response content will be immediately downloaded.