2013-05-31 62 views
0

在python3,我想看看在的urlopen調試不顯示標頭值

>>from urllib.request import urlopen 
>> url1='http://diveintopython3.org/examples/feed.xml' 
>>from http.client import HTTPConnection as httpcon 
>>httpcon.debuglevel = 1 
>>resp1 = urlopen(url1) 

由此產生

send: b'GET /examples/feed.xml HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: diveintopython3.org\r\nUser-Agent: Python-urllib/3.3\r\nConnection: close\r\n\r\n' 
reply: 'HTTP/1.1 200 OK\r\n' 
header: Cache-Control header: Pragma header: Content-Type header: Expires header: Server header: X-AspNet-Version header: X-Powered-By header: Date header: Content-Length header: Age header: Connection 

而捲曲帶給我的頭值

請求發送的標頭值
$curl -I http://diveintopython3.org/examples/feed.xml 
HTTP/1.1 200 OK 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Length: 783 
Content-Type: text/html; charset=utf-8 
Expires: -1 
Server: ATS/3.2.4 
X-AspNet-Version: 4.0.30319 
X-Powered-By: ASP.NET 
Date: Fri, 31 May 2013 02:48:12 GMT 
Age: 0 
Connection: keep-alive 

我應該怎麼做才能在python3中列出頭文件值(作爲調試信息)?

回答

0

urllib.request.urlopen返回的對象是http.client.HTTPResponse對象,您可以使用它定義的所有方法。有一個叫getheaders這你想要做什麼:

>>> from urllib.request import urlopen 
>>> url1 = 'http://diveintopython3.org/examples/feed.xml' 
>>> r = urlopen(url1) 
>>> r.getheaders() 
[('Cache-Control', 'no-cache'), ('Pragma', 'no-cache'), ('Content-Type', 'text/html; charset=utf-8'), ('Expires', '-1'), ('Server', 'ATS/3.2.4'), ('X-AspNet-Version', '4.0.30319'), ('X-Powered-By', 'ASP.NET'), ('Date', 'Fri, 31 May 2013 11:43:46 GMT'), ('Content-Length', '783'), ('Age', '0'), ('Connection', 'close')] 

更多相關信息,請參見http.client文檔。