[英]How to Solve [SSL: CERTIFICATE_VERIFY_FAILED] Error when Using urllib without bypassing SSL verification
import urllib.request
import json
gojson = 'https://nominatim.openstreetmap.org/details.php?osmtype=W&osmid=17025436&class=highway&addressdetails=1&hierarchy=0&group_hierarchy=1&format=json&polygon_geojson=1'
res_body = urllib.request.urlopen(gojson).read()
错误:
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)>
我知道我可以通过使用以下代码来解决错误:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
但我更想知道如何解决这个问题。 我在网上搜索时找不到解决方案。 有什么建议吗?
一种方法是将urllib.request.urlopen()
可选的“ cafile ”参数与受信任的 CA 包的完整路径一起传递,例如由certifi生成的“cacert.pem”文件。 这可以通过certifi包中的certifi.where()
来完成。
示例,使用您的代码片段:
import certifi #added import
import json
import urllib.request
gojson = 'https://nominatim.openstreetmap.org/details.php?osmtype=W&osmid=17025436&class=highway&addressdetails=1&hierarchy=0&group_hierarchy=1&format=json&polygon_geojson=1'
res_body = urllib.request.urlopen(gojson, cafile=certifi.where()).read() #modified function call to add cafile argument
当然,你可以使用任何你想要的文件或路径,我只是提供了上面的例子,因为它需要在本地文件系统上进行较少的探索,并且对于最少的工作量来说似乎相对值得信赖。 使用经过验证的/受信任的 CA 包而不是关闭 ssl 验证通常是一种更安全的做法,这是一个很好的问题。
我的环境:macOS Big Sur,Python 3.9
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.