【问题标题】:urllib.request in Python 3 - check if file is downloadablePython 3 中的 urllib.request - 检查文件是否可下载
【发布时间】:2020-03-18 09:27:01
【问题描述】:

在 Python 3.8.2 中,我下载文件:

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

如何在不下载的情况下检查 url_address 上的文件是否可下载? 我尝试了 try 声明。它只会在无法下载文件时引发错误,但当来自给定 URL 地址的文件可下载时,它总是会下载。

【问题讨论】:

    标签: python-3.x http download urllib urlretrieve


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2013-03-28
      • 1970-01-01
      • 2013-05-18
      • 2014-07-05
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      相关资源
      最近更新 更多