Get file size using python-requests, while only getting the header

前端 未结 3 634
醉酒成梦
醉酒成梦 2020-12-07 20:14

I have looked at the requests documentation, but I can\'t seem to find anything. How do I only request the header, so I can assess filesize?

3条回答
  •  眼角桃花
    2020-12-07 21:06

    use requests.get(url, stream=True).headers['Content-length']

    stream=True means when function returns, only the response header is downloaded, response body is not.

    Both requests.get and request.head can get you headers but there's an advantage of using get

    1. get is more flexible, if you want to download the response body after inspecting the length, you can start by simply access the content property or using an iterator which will download the content in chunks
    2. "HEAD request SHOULD be identical to the information sent in response to a GET request." but its not always the case.

    here is an example of getting the length of a MIT open course video

    MitOpenCourseUrl = "http://www.archive.org/download/MIT6.006F11/MIT6_006F11_lec01_300k.mp4"
    resHead = requests.head(MitOpenCourseUrl)
    resGet = requests.get(MitOpenCourseUrl,stream=True)
    resHead.headers['Content-length'] # output 169
    resGet.headers['Content-length'] # output 121291539
    

提交回复
热议问题