【问题标题】:python requests check if a file downloaded correctlypython请求检查文件是否正确下载
【发布时间】:2014-07-05 21:54:46
【问题描述】:

我正在使用requests lib 从站点下载一些图像。
我的代码会在下载后检查文件大小。
示例代码:

def download(url, store_dir):
    r = requests.get(url, headers=headers, proxies=proxies)

    filename = r.headers.get('content-disposition').split('=')[1]

    real_length = int(r.headers.get('content-length'))

    wholepath = os.path.join(store_dir, filename)

    with open(wholepath, 'wb') as f:
        f.write(r.content)
        f.close()

    if os.path.getsize(wholepath) != real_length:
        print('size error')
        print('status_code: %s' %r.status_code)
        print('headers: %s' %r.headers)
        print('url"%s' % url)
        print('orgin:', r.headers['content-length'], 'now',os.path.getsize(wholepath))
        self.download(url, store_dir)

但我通常发现即使os.path.getsize(wholepath) == real_length 图像文件已损坏。
我该如何解决这个问题?

【问题讨论】:

    标签: python python-2.7 download python-requests


    【解决方案1】:

    将近 4 年。我忘记了这个问题,直到今天收到反对票。

    让我结束这个问题:

    没有完美的方法来验证没有哈希字符串的文件。

    但是如果你从一个网站爬取文件,你可以尝试在页面/url上查找是否有一个看起来像md5/sha1的字符串,然后尝试一下。幸运的是,它是文件哈希,您可以通过它验证文件。没有运气,没有办法。

    【讨论】:

      猜你喜欢
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2020-07-12
      • 2012-04-10
      • 1970-01-01
      • 2013-05-18
      相关资源
      最近更新 更多