我有一个链接列表,我正在尝试获取其大小,以确定每个文件需要多少计算资源。是否可以只使用get请求或类似的方法来获取文件大小?
以下是其中一个链接的示例:https://sra-download.ncbi.nlm.nih.gov/traces/sra46/SRR/005150/SRR5273887
谢谢
发布于 2019-03-19 01:11:49
为此,使用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'发布于 2019-03-19 01:10:29
您需要使用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?。
发布于 2019-03-19 01:03:43
如果您使用的是Python3,则可以使用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: bytesContent-Length属性是以字节为单位的文件大小。
https://stackoverflow.com/questions/55226378
复制相似问题