18

在 python 2 中,可以通过执行从 urllib 获取调试输出

import httplib
import urllib
httplib.HTTPConnection.debuglevel = 1
response = urllib.urlopen('http://example.com').read()

但是,在 python 3 中,这似乎已移至

http.client.HTTPConnection.set_debuglevel(level)

但是,我直接使用 urllib 而不是 http.client 。如何设置它以便我的 http 请求以这种方式显示调试信息?

到目前为止,这是我正在使用的内容。如果我希望能够获得调试信息,最好的方法是什么?

#Request Login page
cookiejar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar))
request = urllib.request.Request(options.uri)
add_std_headers(request)
response = opener.open(request)
response_string = response.read().decode("utf8")
# ...
4

2 回答 2

18

你第一次是对的。您只需http.client.HTTPConnection.debuglevel = 1在文件开头添加该行即可在应用程序范围内打开 HTTP 调试。urllib.request仍然使用http.client.

似乎还有一种方法可以为单个处理程序设置调试级别(通过创建urllib.request.HTTPHandler(debuglevel=1)和构建一个打开器),但是在我安装的 Python3(3.0b3)上它实际上并没有实现。我想这在最近的版本中发生了变化!

于 2009-04-26T00:34:27.000 回答
0

https://github.com/urllib3/urllib3/issues/107中,SmithSamuelM 建议

if self.debug:
            import httplib
            httplib.HTTPConnection.debuglevel = 5
            requests.packages.urllib3.add_stderr_logger()
于 2020-06-10T05:57:46.433 回答