2011-04-11 162 views
-2

我做了一个httprequest,我想获取内容长度。 我正在写python,我尝试request.getContentLength但它不起作用。Python获取内容长度

你知道该怎么办?

感谢

+2

你能否包含你的代码片段,以便我们可以更好地看到你在做什么。 – Bemmu 2011-04-11 02:02:05

+0

only this:result = request.GET(“http:// ip-ad”) 打印结果 print result.getContentLength() print result.getData() – tranen 2011-04-11 02:08:52

+1

除非您提供自己的代码,否则不要期待帮助。 – 2011-04-11 03:09:45

回答

-3

getContentLength,它ressembles到Java名称

在Python,一个HTTP请求之后,获得所获取的内容的大小:

import urllib 

url = 'http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx' 
data = urllib.urlopen(url).read() 
print len(data) 

这将显示

174525 
+0

你可以得到内容长度和下载整个页面。 – raju 2012-11-01 18:25:13

6

如果你想要的只是内容长度,那么你可以做一个HEAD请求美东时间。 HEAD请求只会检索标题而不是整个文件。

import httplib 
conn = httplib.HTTPSConnection("example.com") 
conn.request("HEAD", "/path/tofile.txt") 
response = conn.getresponse() 
headers = response.getheaders() 
print headers 

内容长度在headers之内。

+2

我更喜欢这个解决方案,但是如果安装httplib不是一个选项,它也可以用urllib2完成:http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request -in的Python/2070916#2070916 – dnet 2011-09-29 11:28:30