我有一个使用 urllib2 的 Python Web 客户端。将 HTTP 标头添加到我的传出请求中非常容易。我只是创建一个我想要添加的标头的字典,并将其传递给请求初始值设定项。
但是,其他“标准”HTTP 标头以及我显式添加的自定义标头都会添加到请求中。当我使用 Wireshark 嗅探请求时,除了我自己添加的标头之外,我还看到标头。我的问题是如何访问这些标头?我想记录每个请求(包括完整的 HTTP 标头集),但不知道如何记录。
有什么指点吗?
简而言之:如何从 urllib2 创建的 HTTP 请求中获取所有传出标头?
如果您想查看发送出去的文本 HTTP 请求,并因此查看与网络上所表示的完全相同的每个最后标头,那么您可以告诉
urllib2
使用您自己的 HTTPHandler
版本来打印(或保存,或其他)传出的 HTTP 请求。
# For Python 2, switch these imports to:
#
# import httplib as client
# import urllib2 as request
from http import client
from urllib import request
class MyHTTPConnection(client.HTTPConnection):
def send(self, s):
print(s.decode('utf-8')) # or save them, or whatever
client.HTTPConnection.send(self, s)
class MyHTTPHandler(request.HTTPHandler):
def http_open(self, req):
return self.do_open(MyHTTPConnection, req)
opener = request.build_opener(MyHTTPHandler)
response = opener.open('http://www.google.com/')
运行这段代码的结果是:
GET / HTTP/1.1
Accept-Encoding: identity
Host: www.google.com
User-Agent: Python-urllib/3.9
Connection: close
urllib2 库使用 OpenerDirector 对象来处理实际的打开。幸运的是,Python 库提供了默认值,因此您不必这样做。然而,正是这些 OpenerDirector 对象添加了额外的标头。
在发送请求后查看它们是什么(例如,以便您可以记录它):
req = urllib2.Request(url='http://google.com')
response = urllib2.urlopen(req)
print req.unredirected_hdrs
(produces {'Host': 'google.com', 'User-agent': 'Python-urllib/2.5'} etc)
unredirected_hdrs 是 OpenerDirectors 转储额外标头的地方。只需查看
req.headers
将仅显示您自己的标头 - 库不会为您留下那些不受干扰的标头。
如果您需要在发送请求之前查看标头,则需要子类化 OpenerDirector 才能拦截传输。
希望有帮助。
编辑:我忘了提及,一旦发送请求,
req.header_items()
将为您提供所有标头的元组列表,其中包括您自己的标头和 OpenerDirector 添加的标头。我应该首先提到这一点,因为它是最直接的:-) 抱歉。
编辑2:在您询问有关定义自己的处理程序的示例之后,这是我提出的示例。对请求链进行任何胡闹的问题是,我们需要确保处理程序对于多个请求是安全的,这就是为什么我对直接替换 HTTPConnection 类上的 putheader 的定义感到不舒服。
遗憾的是,由于 HTTPConnection 和 AbstractHTTPHandler 的内部结构非常内部,我们必须从 python 库中复制大部分代码来注入我们的自定义行为。假设我没有犯错,并且这与我在 5 分钟测试中的效果一样好,如果您将 Python 版本更新到修订号(即:2.5.x 到 2.5.y 或2.5 至 2.6 等)。
因此我应该提到我使用的是 Python 2.5.1。如果您有 2.6,尤其是 3.0,您可能需要相应调整。
如果这不起作用,请告诉我。我对这个问题太感兴趣了:
import urllib2
import httplib
import socket
class CustomHTTPConnection(httplib.HTTPConnection):
def __init__(self, *args, **kwargs):
httplib.HTTPConnection.__init__(self, *args, **kwargs)
self.stored_headers = []
def putheader(self, header, value):
self.stored_headers.append((header, value))
httplib.HTTPConnection.putheader(self, header, value)
class HTTPCaptureHeaderHandler(urllib2.AbstractHTTPHandler):
def http_open(self, req):
return self.do_open(CustomHTTPConnection, req)
http_request = urllib2.AbstractHTTPHandler.do_request_
def do_open(self, http_class, req):
# All code here lifted directly from the python library
host = req.get_host()
if not host:
raise URLError('no host given')
h = http_class(host) # will parse host:port
h.set_debuglevel(self._debuglevel)
headers = dict(req.headers)
headers.update(req.unredirected_hdrs)
headers["Connection"] = "close"
headers = dict(
(name.title(), val) for name, val in headers.items())
try:
h.request(req.get_method(), req.get_selector(), req.data, headers)
r = h.getresponse()
except socket.error, err: # XXX what error?
raise urllib2.URLError(err)
r.recv = r.read
fp = socket._fileobject(r, close=True)
resp = urllib2.addinfourl(fp, r.msg, req.get_full_url())
resp.code = r.status
resp.msg = r.reason
# This is the line we're adding
req.all_sent_headers = h.stored_headers
return resp
my_handler = HTTPCaptureHeaderHandler()
opener = urllib2.OpenerDirector()
opener.add_handler(my_handler)
req = urllib2.Request(url='http://www.google.com')
resp = opener.open(req)
print req.all_sent_headers
shows: [('Accept-Encoding', 'identity'), ('Host', 'www.google.com'), ('Connection', 'close'), ('User-Agent', 'Python-urllib/2.5')]
这样的事情怎么样:
import urllib2
import httplib
old_putheader = httplib.HTTPConnection.putheader
def putheader(self, header, value):
print header, value
old_putheader(self, header, value)
httplib.HTTPConnection.putheader = putheader
urllib2.urlopen('http://www.google.com')
低级解决方案:
import httplib
class HTTPConnection2(httplib.HTTPConnection):
def __init__(self, *args, **kwargs):
httplib.HTTPConnection.__init__(self, *args, **kwargs)
self._request_headers = []
self._request_header = None
def putheader(self, header, value):
self._request_headers.append((header, value))
httplib.HTTPConnection.putheader(self, header, value)
def send(self, s):
self._request_header = s
httplib.HTTPConnection.send(self, s)
def getresponse(self, *args, **kwargs):
response = httplib.HTTPConnection.getresponse(self, *args, **kwargs)
response.request_headers = self._request_headers
response.request_header = self._request_header
return response
示例:
conn = HTTPConnection2("www.python.org")
conn.request("GET", "/index.html", headers={
"User-agent": "test",
"Referer": "/",
})
response = conn.getresponse()
响应.状态,响应.原因:
1: 200 OK
response.request_headers:
[('Host', 'www.python.org'), ('Accept-Encoding', 'identity'), ('Referer', '/'), ('User-agent', 'test')]
response.request_header:
GET /index.html HTTP/1.1
Host: www.python.org
Accept-Encoding: identity
Referer: /
User-agent: test
另一个解决方案,女巫使用了如何在 urllib2 请求中获取默认标头?但不从 std-lib 复制代码:
class HTTPConnection2(httplib.HTTPConnection):
"""
Like httplib.HTTPConnection but stores the request headers.
Used in HTTPConnection3(), see below.
"""
def __init__(self, *args, **kwargs):
httplib.HTTPConnection.__init__(self, *args, **kwargs)
self.request_headers = []
self.request_header = ""
def putheader(self, header, value):
self.request_headers.append((header, value))
httplib.HTTPConnection.putheader(self, header, value)
def send(self, s):
self.request_header = s
httplib.HTTPConnection.send(self, s)
class HTTPConnection3(object):
"""
Wrapper around HTTPConnection2
Used in HTTPHandler2(), see below.
"""
def __call__(self, *args, **kwargs):
"""
instance made in urllib2.HTTPHandler.do_open()
"""
self._conn = HTTPConnection2(*args, **kwargs)
self.request_headers = self._conn.request_headers
self.request_header = self._conn.request_header
return self
def __getattribute__(self, name):
"""
Redirect attribute access to the local HTTPConnection() instance.
"""
if name == "_conn":
return object.__getattribute__(self, name)
else:
return getattr(self._conn, name)
class HTTPHandler2(urllib2.HTTPHandler):
"""
A HTTPHandler which stores the request headers.
Used HTTPConnection3, see above.
>>> opener = urllib2.build_opener(HTTPHandler2)
>>> opener.addheaders = [("User-agent", "Python test")]
>>> response = opener.open('http://www.python.org/')
Get the request headers as a list build with HTTPConnection.putheader():
>>> response.request_headers
[('Accept-Encoding', 'identity'), ('Host', 'www.python.org'), ('Connection', 'close'), ('User-Agent', 'Python test')]
>>> response.request_header
'GET / HTTP/1.1\\r\\nAccept-Encoding: identity\\r\\nHost: www.python.org\\r\\nConnection: close\\r\\nUser-Agent: Python test\\r\\n\\r\\n'
"""
def http_open(self, req):
conn_instance = HTTPConnection3()
response = self.do_open(conn_instance, req)
response.request_headers = conn_instance.request_headers
response.request_header = conn_instance.request_header
return response
编辑:更新来源
参见 urllib2.py:do_request (第 1044 行(1067))和 urllib2.py:do_open (第 1073 行) (第293行)self.addheaders = [('User-agent', client_version)](仅添加'User-agent')
在我看来,您正在寻找响应对象的标头,其中包括
Connection: close
等。这些标头位于 urlopen 返回的对象中。获取它们很容易:
from urllib2 import urlopen
req = urlopen("http://www.google.com")
print req.headers.headers
req.headers
是 httplib.HTTPMessage 的实例