0

在 python3 中,我试图查看请求中发送的标头值

>>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 给了我标题值

$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 中列出标头值(作为调试信息)?

4

1 回答 1

0

作为对象返回urllib.request.urlopenhttp.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文档。

于 2013-05-31T11:46:32.993 回答