首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果不下载python,如何从链接中获取文件大小?

如果不下载python,如何从链接中获取文件大小?
EN

Stack Overflow用户
提问于 2019-03-19 00:54:57
回答 3查看 5.1K关注 0票数 5

我有一个链接列表,我正在尝试获取其大小,以确定每个文件需要多少计算资源。是否可以只使用get请求或类似的方法来获取文件大小?

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

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-19 01:11:49

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

代码语言:javascript
复制
$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中:

代码语言:javascript
复制
>>> 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'
票数 7
EN

Stack Overflow用户

发布于 2019-03-19 01:10:29

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

代码语言:javascript
复制
#!/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?

票数 8
EN

Stack Overflow用户

发布于 2019-03-19 01:03:43

如果您使用的是Python3,则可以使用urllib.request中的urlopen执行此操作

代码语言:javascript
复制
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)

这将输出:

代码语言:javascript
复制
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属性是以字节为单位的文件大小。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55226378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档