I too was looking for a solution and found one. Use requests
with stream=True
and tqdm
.
To install tqdm with python3, use:
python3 -m pip install tqdm
Code to download a video from MITOpenCourseWare:
import requests
from tqdm import tqdm
link = 'http://www.archive.org/download/MIT6.006F11/MIT6_006F11_lec01_300k.mp4'
filename = 'video.mp4'
response = requests.get(link, stream=True)
if response.status_code == requests.codes.ok:
total_size = int(response.headers.get('Content-Length', 0))
downloaded_size = 0
print(f'contentLength: {total_size} MB')
with open(filename, 'wb') as handle,\
tqdm(unit='B', total=total_size, desc=filename, unit_scale=True, unit_divisor=1024) as bar:
for chunk in response.iter_content(chunk_size=1024*1024):
size = handle.write(chunk)
bar.update(size)
downloaded_size += size
The variable downloaded_size
for each loop gives the current downloaded size and total_size
gives the total size.
Assumptions:
- The website responds with a
Content-Length