[Python]_[网络]_[关于如何使用urllib3库和访问https的问题]

版权声明:本文为博主原创文章,未经博主允许不得转载。 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.urllib3api已经和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)

参考

Certificate verification

猜你喜欢

转载自blog.csdn.net/infoworld/article/details/84669500