2012-06-16 100 views
2

當試圖使用python中的urllib2檢查某些網頁的'content-length'標題時,標題丟失。例如,來自google.com的回覆缺少此標題。任何想法爲什麼?使用python的urllib2時缺少'content-length'標題urlopen

實施例:

r = urllib2.urlopen('http://www.google.com') 
i = r.info() 
print i.keys() 

給出:

['x-xss-protection', 'set-cookie', 'expires', 'server', 'connection', 'cache-control', 'date', 'p3p', 'content-type', 'x-frame-options'] 

回答

1

你可以看到here,一個HTTP響應可以包含Content-LengthTransfer-Encoding: chunked

但是,當在標頭中使用Transfer-Encoding: chunked時,在標題後面,您將得到一個十六進制字符串,如果轉換爲十進制,則會給出下一個塊的長度。在最後一個塊之後,你會得到一個0這個值,這意味着你已經達到了文件的末尾。

您可以使用正則表達式來得到這個十六進制值(不是雖然必須)

read = #string containing a line or a part of the http response 
hexPat = re.compile(r'([0-9A-F]+)\r\n', re.I) 
match = re.search(hexPat, read) 
chunkLen = int(match.group(1), 16) #converts hexadecimal to decimal 

,或者你可以只讀取第一個十六進制值,得到的第一個塊的長度和接收塊,然後獲得下一個塊的長度等等,直到找到0

+0

感謝有關傳輸編碼的信息。你知道如何通過urllib2在你的代碼片段中獲取'讀'字符串嗎?如果我在上面的示例中嘗試使用r.read(),我會得到google.com的完整html代碼,並且沒有十六進制前綴告訴我塊大小或任何內容。 urllib2是否過高,無法一次檢查一個組塊的響應? – user1369195

+0

@ user1369195我不確定,但我認爲它太高級別。 當我使用它時,我正在使用套接字進行低級別的工作。 –

0

一個HEAD響應的內容 - 長度應,但並不總是確實包括一個GET響應的Content-Length值:

Stack Overflow做:

> telnet stackoverflow.com 80 
HEAD/HTTP/1.1 
Host: stackoverflow.com 


HTTP/1.1 200 OK 
Cache-Control: public, max-age=60 
Content-Length: 362245       <-------- 
Content-Type: text/html; charset=utf-8 
Expires: Mon, 04 Oct 2010 11:51:49 GMT 
Last-Modified: Mon, 04 Oct 2010 11:50:49 GMT 
Vary: * 
Date: Mon, 04 Oct 2010 11:50:49 GMT 

谷歌不會:

> telnet www.google.com 80 
HEAD/HTTP/1.1 
Host: www.google.ie 


HTTP/1.1 200 OK 
Date: Mon, 04 Oct 2010 11:55:36 GMT 
Expires: -1 
Cache-Control: private, max-age=0 
Content-Type: text/html; charset=ISO-8859-1 
Server: gws 
X-XSS-Protection: 1; mode=block 
Transfer-Encoding: chunked 
+0

你知道有什麼方法可以在下載完整內容之前檢查頁面的大小嗎?當'content-length'頭部缺失時? – user1369195

相關問題