Łukasz Ungier
Łukasz Ungier

Reputation: 71

urllib.request in Python 3 - check if file is downloadable

In Python 3.8.2 I download files with:

import urllib.request
urllib.request.urlretrieve(url_address, file_name)

How can I check if file on url_address is downloadable without downloading it? I tried with try statement. It only raises Error when it can't download files, but it always downloads when the file from a given URL address is downloadable.

Upvotes: 4

Views: 1030

Answers (1)

Łukasz Ungier
Łukasz Ungier

Reputation: 71

I solved this with. It prints "content-type" attribute from http header.

try:
    site = urllib.request.urlopen(url)
    header = site.info()
    print(header["content-type"])
except Exception as e:
    print(e)

and then I download as always:

urllib.request.urlretrieve(url, file_name)

Upvotes: 2

Related Questions