2011-06-14 84 views

回答

21

一个简单的方法见请求(和响应标头)是使调试输出:

opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)) 

然后,可以看到的精确头发送/收到:

>>> opener.open('http://python.org') 
send: 'GET/HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: python.org\r\nConnection: close\r\nUser-Agent: Python-urllib/2.7\r\n\r\n' 
reply: 'HTTP/1.1 200 OK\r\n' 
header: Date: Tue, 14 Jun 2011 08:23:35 GMT 
header: Server: Apache/2.2.16 (Debian) 
header: Last-Modified: Mon, 13 Jun 2011 19:41:35 GMT 
header: ETag: "105800d-486d-4a59d1b6699c0" 
header: Accept-Ranges: bytes 
header: Content-Length: 18541 
header: Connection: close 
header: Content-Type: text/html 
header: X-Pad: avoid browser bug 
<addinfourl at 140175550177224 whose fp = <socket._fileobject object at 0x7f7d29c3d5d0>> 

还可以设置在提出请求之前使用urllib2.Request对象标题(并覆盖默认标题,尽管事先不在标题字典中):

>>> req = urllib2.Request(url='http://python.org') 
>>> req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.0)') 
>>> req.headers 
{'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.0)'} 
+11

有没有什么方法可以查看发送请求之前发送的标题?我想模拟发送请求以获取将*发送的头(而不实际发送它)。 – Raj 2011-08-09 20:53:08

+1

请注意,如果您需要将其他处理器添加到'build_opener',则可以将多个处理器传递给'build_opener'函数。例如,为了还包括一个cookie处理器,你可以执行'opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar),urllib2.HTTPHandler(debuglevel = 1))'。 – dionyziz 2017-01-11 05:24:16