2

I am downloading video using python requests module. I want to know how much content is received currently while downloading like we see in browsers etc. x bytes downloaded of y bytes.

I have attached the code below what I'm using. How can I achieve what I said above?

print(f'[+] Downloading "{file}" ({sizeInMb} MB)...')
with requests.get(url, stream=True) as r:
    with open(filePath, 'wb+') as f:
        shutil.copyfileobj(r.raw, f)
        print(f'[-] Downloaded "{file}".')
        downloadCount += 1
Aashif Ali
  • 53
  • 4

2 Answers2

2

To have a download bar, you can use the wget module in Python.

import wget

url = 'https://www.tutorialspoint.com/python3/python3_tutorial.pdf'
file_name = wget.download(url)

print()
print(file_name)

I used a random PDF as a reference here. You can also update the downloaded file path and filename in the wget.download function, using the out argument.

Final Output:

100% [..........................................................................] 1015876 / 1015876
python3_tutorial.pdf
Zero
  • 1,807
  • 1
  • 6
  • 17
1

you can use the iter_content() method of the requests library to download the video as chunks and track the progress of the download. The iter_content() method returns a generator that yields the chunks of the file as they are downloaded. You can use the len() function to get the total size of the file, and then use a counter to track how many bytes have been downloaded so far.

Here is an example of how to do this:

import requests

def download_video(url):
    response = requests.get(url, stream=True)
    file_size = int(response.headers['Content-Length'])
    downloaded = 0
    with open('video.mp4', 'wb') as f:
        for chunk in response.iter_content(chunk_size=1024):
            downloaded += len(chunk)
            print(f'Downloaded {downloaded}/{file_size} bytes')
            f.write(chunk)

if __name__ == '__main__':
    download_video('https://www.example.com/video.mp4')

output be like:

Downloaded 0/1024000 bytes
Downloaded 1024000/1024000 bytes