python使用SSL问题解决

python使用SSL问题解决
  • 1、关于requests.exceptions.SSLError: HTTPSConnectionPool(host=’XXX’, port=443)问题

    解决方法如下:

    1)先检查是否已安装requests的依赖安装包:

    
    pip install cryptography
    pip install pyOpenSSL
    pip install certifi
    				

    2)如果已经安装依赖安装包,还会报错,则在请求后面加上verify=False就可以

  • 2、关于证书不匹配问题:SSLError(CertificateError(“hostname ‘192.168.1.223’ doesn’t match ‘test.xxx.org'”

    解决方法如下:

    1)对于python自带的urllib库:

    
    import ssl
    ssl.match_hostname = lambda cert, hostname: True
    				

    2)对于requests库

    
    requests.get(url='https://192.168.1.223',verify=False)
    				
  • 3、证书(certificate)验证失败问题
    
    from urllib.request import urlopen
    html = urlopen('https://en.wikipedia.org/wiki/Kevin_Bacon',)
    				

    报错如下urllib.error.URLError: urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

    解决方法:

    1)证书上下文

    
    from urllib.request import urlopen
    import ssl
    # 导入头文件
    # 生成证书上下文(unverified 就是不验证https证书)
    context = ssl._create_unverified_context()
    # 改为如下即可
    html = urlopen('https://en.wikipedia.org/wiki/Kevin_Bacon', context=context)
    				

    2)重写https默认的验证方式

    
    from urllib.request import urlopen
    import ssl
    ssl._create_default_https_context = ssl._create_unverified_context
    html = urlopen('https://en.wikipedia.org/wiki/Kevin_Bacon',)
    				

发表回复

您的电子邮箱地址不会被公开。