场景
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.youkuaiyun.com/infoworld"
test_urllib3(url)

本文介绍如何在Python3中使用urllib3库进行安全的HTTPS请求,避免不安全的警告,通过安装pyOpenSSL、cryptography、idna和certifi等包,确保网络请求的安全性,并提供了一个示例代码。
1157

被折叠的 条评论
为什么被折叠?



