版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/infoworld/article/details/84669500
场景
1.在使用Python2 urllib2
访问如今的大部分https
网络时, 会输出不支持https
的警告, 这部分https
使用的是TLS
协议, 而Python2
已经不再维护, 官方已经不支持. 如果需要支持,会提醒需要使用urllib3
, 而urllib3
只支持Python3
.
说明
1.在使用urllib3
时, 会输出以下的警告; urllib3默认是不验证https
请求的, 这样会容易被攻击(网络欺骗). 所以安全方面最好还是解决这个警告, 使用安全证书.
InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
2.要使用安全证书, 需要安装以下包:
# pyOpenSSL, cryptography, idna, and certifi
pip install pyOpenSSL
...
3.如果pycharm
里找不到urllib3 certifi
的话, 需要配置解释器使用标准目录下的.
4.urllib3
的api
已经和urllib2
不同了, Python3
默认是小写类名和方法.
例子
1.对于requeset
返回的response.data
, 是字节数据.
import urllib3
import urllib3.contrib.pyopenssl
import certifi
def test_urllib3(url):
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"
}
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
response = http.request('GET', url, None, header)
data = response.data.decode('utf-8') # 注意, 返回的是字节数据.需要转码.
print (data) # 打印网页的内容
if __name__ == "__main__":
urllib3.contrib.pyopenssl.inject_into_urllib3()
url = "https://blog.csdn.net/infoworld"
test_urllib3(url)