Oleg Kovalov
Oleg Kovalov

Reputation: 762

How can I get the file size on the Internet knowing only the URL

I want to get the size of an http://.. file before I download it. I don't know how to use http request.

Thanks!

Upvotes: 2

Views: 4769

Answers (4)

Cabu
Cabu

Reputation: 51

Here the complete answer:

import urllib2
f = urllib2.urlopen ("http://your-url")
if "Content-Length" in f.headers:
    size = int (f.headers["Content-Length"])
else:
    size = len (f.read ());
print size

Upvotes: 5

Sjoerd
Sjoerd

Reputation: 75609

Not all pages have a content-length header. In that case, the only option is to read the whole page:

len(urllib2.urlopen('http://www.google.com').read());

Upvotes: 4

Uku Loskit
Uku Loskit

Reputation: 42040

import urllib2
f = urllib2.urlopen("http://your-url")
size= f.headers["Content-Length"]
print size

Upvotes: 13

obeattie
obeattie

Reputation: 3344

The HTTP HEAD method was invented for scenarios like this (wanting to know data about a response without fetching the response itself). Provided the server returns a Content-Length header (and supports HEAD), then you can find out the size of the file (in octets) by looking at the Content-Length returned.

Upvotes: 12

Related Questions