【发布时间】:2019-03-18 16:54:57
【问题描述】:
我有一个链接列表,我试图获取其大小以确定每个文件需要多少计算资源。是否可以通过获取请求或类似的方式获取文件大小?
这是其中一个链接的示例:https://sra-download.ncbi.nlm.nih.gov/traces/sra46/SRR/005150/SRR5273887
谢谢
【问题讨论】:
-
你可以看看here.
我有一个链接列表,我试图获取其大小以确定每个文件需要多少计算资源。是否可以通过获取请求或类似的方式获取文件大小?
这是其中一个链接的示例:https://sra-download.ncbi.nlm.nih.gov/traces/sra46/SRR/005150/SRR5273887
谢谢
【问题讨论】:
为此,请使用 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 方法。该示例使用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?。
【讨论】:
如果您使用的是 Python 3,则可以使用来自 urllib.request 的 urlopen 来完成:
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 请求,实际上会下载文档。