【问题标题】:How can I get the file size from a link without downloading it in python?如何从链接获取文件大小而不用 python 下载?
【发布时间】:2019-03-18 16:54:57
【问题描述】:

我有一个链接列表,我试图获取其大小以确定每个文件需要多少计算资源。是否可以通过获取请求或类似的方式获取文件大小?

这是其中一个链接的示例:https://sra-download.ncbi.nlm.nih.gov/traces/sra46/SRR/005150/SRR5273887

谢谢

【问题讨论】:

  • 你可以看看here.

标签: python get


【解决方案1】:

为此,请使用 HTTP HEAD 方法,该方法仅获取 URL 的标头信息,而不像 HTTP GET 请求那样下载内容。

$curl -I https://sra-download.ncbi.nlm.nih.gov/traces/sra46/SRR/005150/SRR5273887
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 18 Mar 2019 16:56:35 GMT
Content-Type: application/octet-stream
Content-Length: 578220087
Last-Modified: Tue, 21 Feb 2017 12:13:19 GMT
Connection: keep-alive
Accept-Ranges: bytes

文件大小在“Content-Length”标头中。在 Python 3.6 中:

>>> import urllib
>>> req = urllib.request.Request('https://sra-download.ncbi.nlm.nih.gov/traces/sra46/SRR/005150/SRR5273887', 
                                 method='HEAD')
>>> f = urllib.request.urlopen(req)
>>> f.status
200
>>> f.headers['Content-Length']
'578220087'

【讨论】:

  • 请注意,如果远程服务器没有实现 head 您仍然可以通过使用带有 python 请求库的 stream = True 选项来实现类似的功能,如stackoverflow.com/a/44299915 然后在获得后直接关闭每个请求他们的标题。
【解决方案2】:

您需要使用HEAD 方法。该示例使用requests (pip install requests)。

#!/usr/bin/env python
# display URL file size without downloading

import sys
import requests

# pass URL as first argument
response = requests.head(sys.argv[1], allow_redirects=True)

size = response.headers.get('content-length', -1)

# size in megabytes (Python 2, 3)
print('{:<40}: {:.2f} MB'.format('FILE SIZE', int(size) / float(1 << 20)))

# size in megabytes (f-string, Python 3 only)
# print(f"{'FILE SIZE':<40}: {int(size) / float(1 << 20):.2f} MB")

如果您需要基于标准库的解决方案,另请参阅 How do you send a HEAD HTTP request in Python 2?

【讨论】:

    【解决方案3】:

    如果您使用的是 Python 3,则可以使用来自 urllib.requesturlopen 来完成:

    from urllib.request import urlopen
    link =  "https://sra-download.ncbi.nlm.nih.gov/traces/sra46/SRR/005150/SRR5273887"
    site = urlopen(link)
    meta = site.info()
    print(meta)
    

    这将输出:

    Server: nginx
    Date: Mon, 18 Mar 2019 17:02:40 GMT
    Content-Type: application/octet-stream
    Content-Length: 578220087
    Last-Modified: Tue, 21 Feb 2017 12:13:19 GMT
    Connection: close
    Accept-Ranges: bytes
    

    Content-Length 属性是以字节为单位的文件大小。

    【讨论】:

    • urlopen 会发出GET 请求,实际上会下载文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2015-06-16
    • 2020-10-13
    • 1970-01-01
    相关资源
    最近更新 更多