Verifying HTTPS certificates with urllib.request

后端 未结 6 709
不知归路
不知归路 2021-01-18 00:07

I am trying to open an https URL using the urlopen method in Python 3\'s urllib.request module. It seems to work fine, but the documentation warns that \"[i]f neither

6条回答
  •  被撕碎了的回忆
    2021-01-18 00:19

    import certifi
    import ssl
    import urllib.request
    try:
        from urllib.request import HTTPSHandler
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        context.options |= ssl.OP_NO_SSLv2
        context.verify_mode = ssl.CERT_REQUIRED
        context.load_verify_locations(certifi.where(), None)
        https_handler = HTTPSHandler(context=context,  check_hostname=True)
        opener = urllib.request.build_opener(https_handler)
    except ImportError:
        opener = urllib.request.build_opener()
    
    opener.addheaders = [('User-agent',  YOUR_USER_AGENT)]
    urllib.request.install_opener(opener)
    

提交回复
热议问题