我想从元变量中获取Content-Length
值。我需要获取我要下载的文件的大小。但是最后一行返回错误,HTTPMessage
对象没有属性getheaders
。
import urllib.request
import http.client
#----HTTP HANDLING PART----
url = "http://client.akamai.com/install/test-objects/10MB.bin"
file_name = url.split('/')[-1]
d = urllib.request.urlopen(url)
f = open(file_name, 'wb')
#----GET FILE SIZE----
meta = d.info()
print ("Download Details", meta)
file_size = int(meta.getheaders("Content-Length")[0])
答案 0 :(得分:11)
看起来您正在使用Python 3,并且已经阅读了Python 2.x的一些代码/文档。记录很少,但Python 3中没有getheaders
方法,只有get_all
方法。
请参阅this bug report。
答案 1 :(得分:6)
代表Content-Length
:
file_size = int(d.getheader('Content-Length'))
答案 2 :(得分:4)
您应该考虑使用Requests
:
import requests
url = "http://client.akamai.com/install/test-objects/10MB.bin"
resp = requests.get(url)
print resp.headers['content-length']
# '10485760'
对于Python 3,请使用:
print(resp.headers['content-length'])
代替。
答案 3 :(得分:1)
将最后一行更改为:
file_size = int(meta.get_all("Content-Length")[0])
答案 4 :(得分:1)
response.headers['Content-Length']
适用于Python 2和3:
#!/usr/bin/env python
from contextlib import closing
try:
from urllib2 import urlopen
except ImportError: # Python 3
from urllib.request import urlopen
with closing(urlopen('http://stackoverflow.com/q/12996274')) as response:
print("File size: " + response.headers['Content-Length'])
答案 5 :(得分:0)
import urllib.request
link = "<url here>"
f = urllib.request.urlopen(link)
meta = f.info()
print (meta.get("Content-length"))
f.close()
使用python 3.x