如何查看 urllib shttp 请求发送回的消息?如果它是简单的http,我只会查看套接字流量,但当然这不适用于https。有没有我可以设置的调试标志来做到这一点?
import urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen("https://example.com/cgi-bin/query", params)
你总是可以做一些mokeypatching
import httplib
# override the HTTPS request class
class DebugHTTPS(httplib.HTTPS):
real_putheader = httplib.HTTPS.putheader
def putheader(self, *args, **kwargs):
print 'putheader(%s,%s)' % (args, kwargs)
result = self.real_putheader(self, *args, **kwargs)
return result
httplib.HTTPS = DebugHTTPS
# set a new default urlopener
import urllib
class DebugOpener(urllib.FancyURLopener):
def open(self, *args, **kwargs):
result = urllib.FancyURLopener.open(self, *args, **kwargs)
print 'response:'
print result.headers
return result
urllib._urlopener = DebugOpener()
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen("https://www.google.com/", params)
给出输出
putheader(('Content-Type', 'application/x-www-form-urlencoded'),{})
putheader(('Content-Length', '21'),{})
putheader(('Host', 'www.google.com'),{})
putheader(('User-Agent', 'Python-urllib/1.17'),{})
response:
Content-Type: text/html; charset=UTF-8
Content-Length: 1363
Date: Sun, 09 Aug 2009 12:49:59 GMT
Server: GFE/2.0
不,没有调试标志可以观看。
你可以使用你最喜欢的调试器。这是最简单的选择。只需在 urlopen 函数中添加一个断点即可。
另一种选择是编写自己的下载功能:
def graburl(url, **params):
print "LOG: Going to %s with %r" % (url, params)
params = urllib.urlencode(params)
return urllib.urlopen(url, params)
并像这样使用它:
f = graburl("https://example.com/cgi-bin/query", spam=1, eggs=2, bacon=0)