我有一个链接列表,我试图获取其大小以确定每个文件需要多少计算资源。是否可以通过 get 请求或类似的东西来获取文件大小?
以下是其中一个链接的示例:https : //sra-download.ncbi.nlm.nih.gov/traces/sra46/SRR/005150/SRR5273887
谢谢
您需要使用该HEAD方法。该示例使用请求 ( pip install requests)。
#!/usr/bin/env python
# display size of remote file 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)
# print size in megabytes
print('\t{:<40}: {:.2f} MB'.format('FILE SIZE', int(size) / float(1 << 20)))
Run Code Online (Sandbox Code Playgroud)
另请参阅如何在 Python 2 中发送 HEAD HTTP 请求?如果您想要基于标准库的解决方案。
为此,请使用 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
Run Code Online (Sandbox Code Playgroud)
文件大小在“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'
Run Code Online (Sandbox Code Playgroud)