0

I'm currently trying to download a video using Python Requests, and I want to find out the size of it first.

import requests

print("STARTING PROGRAM...")

req = requests.get("https://www.source.com/source.mp4")

The only way I thought of is the following:

for chunk in req.iter_content():
  count+=1
print("FOUND %d CHUNKS" %(count))

But that took quite a long time since I am downloading a 24-min mp4. Is there a better way to do this?

Cyh1368
  • 239
  • 3
  • 10
  • _But that took quite a long time since I am downloading a 24-min mp4._ You might find https://stackoverflow.com/questions/16694907/download-large-file-in-python-with-requests useful. – AMC May 01 '20 at 12:29
  • @AMC Not the real problem I want to solve here, but thanks for the link. – Cyh1368 May 01 '20 at 13:09
  • @Cyh1368 I'm curious, what is the real problem? The answers to this question are still appropriate though, right? – AMC May 01 '20 at 13:10
  • @AMD The problem here is to find a way to get the size of request, though fastening the process can indirectly help too. – Cyh1368 May 02 '20 at 07:38
  • @danill I never really think that much, but that makes sense. – Cyh1368 May 02 '20 at 07:40

2 Answers2

8

Get the head of the file, to get the file size without downloading:

import requests
response = requests.head("https://www.source.com/source.mp4")
print(response.headers)

You should then get something called content-length which is what you want.

Or alternatively, just print the size:

print(response.headers['content-length'])
3

You can send a HEAD request.

import requests

response = requests.head('https://www.source.com/source.mp4')
size = response.headers['content-length']

This will return the size in bytes.

Paul Burkart
  • 53
  • 1
  • 7
  • 1
    Some websites don't set this value. You can see this when your browser just does a loop instead of a proper progress bar. Beware you can't 100% trust headers. – Mies van der Lippe May 01 '20 at 11:32
  • 1
    I don't see how this is better than my answer considering I posted before you... –  May 01 '20 at 11:33