2011-04-11 163 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