我正在尝试制作一个简单的代码,从 .json 文件下载 4365 个文件(.mp4、.wmv、.jpeg 和 .pdf),下载部分已完成,但我想得到一个报告挂钩,告诉我 %, Mb,加速持续时间。
即使有时它会运行,我也会遇到错误:
file "dw.py", line 21, in reporthook
speed = int(progress_size / (1024 * duration))
ZeroDivisionError: float division by zero
这是我的代码:
import urllib.request
import json
import sys
import time
with open('finalsinbin.json') as json_data: # importar toda la lista de videos
items = json.load(json_data)
def reporthook(count, block_size, total_size):
global start_time
if count == 0:
start_time = time.time()
return
duration = time.time() - start_time
progress_size = int(count * block_size)
speed = int(progress_size / (1024 * duration))
percent = min(int(count*blockSize*100/totalSize),100)
sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" % (percent, progress_size / (1024 * 1024), speed, duration))
sys.stdout.flush()
def batch(startAt, stopAt):
a=0
for i in items:
a+=1
if a < startAt or a > stopAt:
continue
num = i['id']
url = i['url']
typ = i['type']
urlfinal = (url + "/" + str(num) + typ)
filename = (str(num) + typ)
print( '[%d] Descargando el archivo %s...' % (a, str(num) + typ))
urllib.request.urlretrieve(urlfinal, filename, reporthook)
batch(1, 100) #download file from n to N