python-快速使用urllib爬取网页(7-DebugLog)

来源:互联网 发布:八皇后问题答案java 编辑:程序博客网 时间:2024/06/11 08:52

有时我们希望在程序运行的过程中,边运行边打印调试日志信息,此时需要开启DeugLog

如何开启DebugLog那?
1、分别使用urllib.request.HTTPHandler()和urllib.request.HTTPSHandler()将debuglevel设置为1
2、使用urllib.request.build_opener()创建自定义的opener对象,并将1中值作为参数
3、用urllib.request.install_opener()创建全局默认的opener对象
4、后续操作

# coding=utf-8import urllib.requesthttphd = urllib.request.HTTPHandler(debuglevel=1)httpshd = urllib.request.HTTPSHandler(debuglevel=1)opener = urllib.request.build_opener(httphd,httpshd)urllib.request.install_opener(opener)data = urllib.request.urlopen("http://www.baidu.com")

通过上面代码,我们可以从执行结果中看到开启了DebugLog

send: b'GET / HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.baidu.com\r\nUser-Agent: Python-urllib/3.6\r\nConnection: close\r\n\r\n'reply: 'HTTP/1.0 200 OK\r\n'header: Server header: Cache-Control header: Pragma header: Content-Type header: Content-Encoding header: Content-Length header: Set-Cookie Process finished with exit code 0