【发布时间】:2020-10-10 20:33:47
【问题描述】:
我是新手程序员,请原谅我的错误。我编写了以下代码来验证网站列表是否仍然有效,并且我的所有工作都基于此问题陈述。
该脚本能够检查大多数网站,但偶然发现https://precisionit.net/ 出现以下错误
<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>
上面的 URL 在 Firefox 和 Chrome 中可以正常打开,但在 Python 代码中无法打开。我已经更新了 certifi 并按照许多人的建议在我的代码中使用了它,但错误不会消失。
我正在使用 Conda Python Env,并且我还执行了以下命令
conda install -c conda-forge certifi
有多个帖子建议运行不适用于 Conda Python 的“Install Certificates.command”,因此我下载了 Python 3.9 安装程序并执行了“Install Certificates.command”并使用 Python 3.9 执行了脚本,但没有成功。我觉得问题是即使使用最新版本的证书,站点证书也没有经过验证。尽管certifi page 说该列表基于 Mozilla 的根证书,但我猜这不是一个精确的副本,这就是 Firefox 能够打开该站点的原因。不确定我的理解是否有意义,并很高兴得到纠正。
在下面粘贴我的脚本。我不知道还需要做什么来解决这个问题,请指教。
import urllib.request
import sys
import certifi
import ssl
def checkURL(url):
try:
hdr = { 'User-Agent' : 'Mozilla/79.0 (Windows NT 6.1; Win64; x64)' }
req=urllib.request.Request(url,headers=hdr)
r = urllib.request.urlopen(req,timeout=100,context=ssl.create_default_context(cafile=certifi.where()))
except Exception as e:
#print(r.read())
print('Failed Connecting to Website')
print(e)
return(1)
print(r.status)
finalurl = r.geturl()
if r.status==200:
print(finalurl)
return(0)
else:
print("Website Not Found")
return(2)
checkURL('https://precisionit.net/')
【问题讨论】:
标签: python-3.x urllib2 client-certificates