覆盖式进度条的实现是由
\r
会退至首行实现,不多BB,我先来个小Demo
给大伙儿练练手!
import time
for i in range (50):
print(i,end="\r")
time.sleep(1) # 睡眠1秒
通过运行以上案例可以看到程序每隔1秒循环覆盖打印
变量i
的值,那如果打打印信息改一下呢?
import time
for i in range (50):
print("█"*i,end="\r")
time.sleep(1) # 睡眠1秒
再次运行你会惊奇的发现进度条效果出来了!是不是很神奇?😎好了,系好安全带咋们要开始冲刺了!
首先咋们先来一段简单的伪代码爬虫
import requests
def Get_Data(url,hander):
return requests.get(url=url,hander=hander)
url = "https://tanblog.cc/upload/2022/09/EADE32CD-73D6-4EF7-84C7-7CEDBC39319D.jpeg"
hander = {
'User-Agent':'Mozilla/5.0'
}
print(Get_Data(url,hander).text)
通过运行以上程序你会发现只有获取完响应体信息才会打印变量而不能实时得到已获取的响应体大小。
缺点
:当请求大文件后会自动开始获取响应体信息,不利于查看与下载进度的展示优点
:如果是小文件可以快速读取响应体信息当然,为避免请求大文件时无法读取响应体的尴尬,可以在请求时加上
stream=True
开启流模式 代码如下:
import requests
def download_file(url,filename):
print("解析完成,正在开始下载!如未下载,请手动打开下方链接下载!")
print("下载地址:%s"%url)
header = {
'User-Agent':'Mozilla/5.0',
'content-type':'application/json; charset=utf-8',
'Referer':'https://www.bilibili.com'
}
print("视频名:%s"%filename)
res = requests.get(url,headers=header,stream=True)
print("视频总大小:%s kb"%str(int(res.headers.get("Content-Length"))/1024))
f = open(filename+".mp4","wb")
write_size = 0
for chunk in res.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
write_size +=1024
print("█" * int(write_size/(int(res.headers.get("Content-Length"))/50))+" "*(50-(int(write_size/(int(res.headers.get("Content-Length"))/50)))) + "已下载 "+str(int(write_size/(int(res.headers.get("Content-Length"))/50))*2)+"%",end="\r")
print("█" * int(write_size/(int(res.headers.get("Content-Length"))/50))+" "*(50-(int(write_size/(int(res.headers.get("Content-Length"))/50)))) +str(int(write_size/(int(res.headers.get("Content-Length"))/50))*2)+"% 下载完成!")
url = "https://upos-sz-mirror08ct.bilivideo.com/upgcxcode/59/28/834082859/834082859_nb3-1-16.mp4?e=ig8euxZM2rNcNbRVhwdVhwdlhWdVhwdVhoNvNC8BqJIzNbfq9rVEuxTEnE8L5F6VnEsSTx0vkX8fqJeYTj_lta53NCM=&uipk=5&nbs=1&deadline=1664521770&gen=playurlv2&os=08ctbv&oi=730467091&trid=70250f21dcda4920a44766a481f8f6c5T&mid=0&platform=html5&upsig=338055a9e8388a07804741c1d94a123d&uparams=e,uipk,nbs,deadline,gen,os,oi,trid,mid,platform&bvc=vod&nettype=0&bw=54744&orderid=0,1&logo=80000000"
filename = "bilibili"
download_file(url,filename)
Tips:当开启
stream=True
流模式后,可以用res.headers.get("Content-Length")
方法获取文件Byte大小! 什么?太复杂了看不懂?没关系,来一个简易版的Demo
video_size = 73206360 # 文件大小
num = 0 # 已读取的大小
code = True
while (code):
num+=1024 # 每读取一次大小为1024Byte,可用chunk_size设置单次读取大小
print("█" * int(num/(video_size/50))+" "*(50-(int(num/(video_size/50)))) + "已下载 "+str(int(num/(video_size/50))*2)+"%",end="\r")
if(num >=video_size):
code = False
print("█" * int(num/(video_size/50))+" "*(50-(int(num/(video_size/50)))) + str(int(num/(video_size/50))*2)+"% 下载完成!")