python urllib,如何观看消息?

2 投票
2 回答
1044 浏览
提问于 2025-04-15 13:28

我怎么能查看通过urllib发送的http请求和返回的消息呢?如果是普通的http请求,我可以直接观察网络连接上的数据流,但对于https就不行了。有没有什么调试选项可以让我做到这一点呢?

import urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen("https://example.com/cgi-bin/query", params)

2 个回答

2

你可以随时进行一些小的修改

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
1

不,这里没有可以用来监控的调试标志。

你可以使用你喜欢的调试工具。这是最简单的方法。只需在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)

撰写回答