python 3 urllib 和 http.client - 无法打开调试消息

python 3 urllib and http.client - unable to turn on debug messages

嗨,Whosebug 社区,

我正在尝试熟悉 urllib.request 标准库并在我的工作脚本中使用它而不是 wget。 但是,我无法在 IDLE 中显示详细的 HTTP 消息,也无法使用脚本文件或手动将命令输入 cmd (py)。

我在 Windows 7 x64 上使用 Python,并尝试了 3.5 和 3.6,包括 3.6.1rc1 但没有成功。

消息应该是使用此命令打开的:

http.client.HTTPConnection.debuglevel = 1

所以这是我的示例代码。它有效,但没有显示详细信息:

import http.client
import urllib.request
http.client.HTTPConnection.debuglevel = 1
response = urllib.request.urlopen('http://whosebug.com')
content = response.read()
with open("stack.html", "wb") as file:
    file.write(content)

我试过使用 .set_debuglevel(1) 但没有成功。 这里似乎有多年的问题 Turning on debug output for python 3 urllib 但是,这与我的情况相同,但无法正常工作。同样在这个问题的评论用户 Yen Chi Hsuan 说这是一个错误并在这里报告 https://bugs.python.org/issue26892

该错误已于 2016 年 6 月关闭,因此我希望在最近的 Python 版本中得到更正。

也许我遗漏了一些东西(例如,需要启用/安装其他东西等等),但我花了一些时间在这上面,结果走到了死胡同。

是否有一种工作方式可以在 Python 3 Windows 上使用 urllib 显示 http 详细信息?

谢谢

编辑:pvg 建议的响应适用于简单示例,但我无法在需要登录的情况下使用它。 HTTPBasicAuthHandler 没有这个 debuglevel 属性。当我尝试将多个处理程序组合到开启器中时,它也不起作用。

userName = 'mylogin'
passWord  = 'mypassword'
top_level_url = 'http://page-to-login.com'

# create an authorization handler
passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, top_level_url, userName, passWord);

auth_handler = urllib.request.HTTPBasicAuthHandler(passman)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)

result = opener.open(top_level_url)
content = result.read()

您链接的问题中的示例显示了工作代码,下面复制了一个版本:

import urllib.request

handler = urllib.request.HTTPHandler(debuglevel=10)
opener = urllib.request.build_opener(handler)
content = opener.open('http://whosebug.com').read()

print(content[0:120])

这很笨拙,另一种选择是使用更友好的库,如 urllib3 (http://urllib3.readthedocs.io/en/latest/)。

import urllib3

urllib3.add_stderr_logger()
http = urllib3.PoolManager()
r = http.request('GET', 'http://whosebug.com')
print(r.status)

如果您决定改用请求库,以下答案描述了如何设置日志记录: