我正在使用 Python 的 urllib2 通过代理发出 HTTP 请求。
proxy_handler = urllib2.ProxyHandler({'http': 'http://myproxy'})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
r = urllib2.urlopen('http://www.pbr.com')
我想记录此请求的所有 header 。我知道使用标准的 HTTPHandler
您可以:
handler = urllib2.HTTPHandler(debuglevel=1)
ProxyHandler
有这样的东西吗?
最佳答案
我很确定 debuglevel
没有记录。
实际上,它实际上是 httplib
的一个特性,urllib2
只是为了方便而转发,因此您不必传递 lambda:httplib.HTTPConnection (debuglevel=1)
代替默认的 httplib.HTTPConnection
作为您的 HTTP 对象工厂。因此,您不太可能在任何其他处理程序中找到任何类似的内容。
但是如果你想依赖一个未记录的实现特性,你真的需要 read the source亲眼看看。
无论如何,向任何处理程序添加调试的明显方法是将它们子类化并自己完成。例如:
class LoggingProxyHandler(urllib2.ProxyHandler):
def proxy_open(self, req, proxy, type):
had_proxy = req.has_proxy()
response = super(LoggingProxyHandler, self).proxy_open(req, proxy, type)
if not had_proxy and req.has_proxy():
# log stuff here
return response
我依赖于 ProxyHandler
调用 set_proxy
的内部知识,如果它没有并且需要一个。相反,检查响应可能更清晰……但您可能无法通过这种方式获得所需的所有信息。
关于python - 如何通过代理调试 urllib2 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26722270/