3

在 Python 3.8.2 我下载文件:

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

如何在不下载的情况下检查 url_address 上的文件是否可下载?我尝试使用try语句。它仅在无法下载文件时引发错误,但当来自给定 URL 地址的文件可下载时,它始终会下载。

4

1 回答 1

1

我解决了这个问题。它从 http 标头打印“内容类型”属性。

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

然后我像往常一样下载:

urllib.request.urlretrieve(url, file_name)
于 2020-03-21T11:37:33.460 回答