python中的许多操作都需要通过https访问.这包括pip安装,或仅使用http.client.HTTPSConnection,或内部使用这些内容的任何模块或应用程序.
如果python是从官方的python pkg安装程序安装的,从https://python.org下载,那么它使用的是openssl的内部版本,并且不包含根证书.任何使用SSL连接的内容都会导致此错误:
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
Run Code Online (Sandbox Code Playgroud)
如何安装根证书以使上述错误消失?
我正在练习'Web Scraping with Python'的代码,我一直有这个证书问题:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
pages = set()
def getLinks(pageUrl):
global pages
html = urlopen("http://en.wikipedia.org"+pageUrl)
bsObj = BeautifulSoup(html)
for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")):
if 'href' in link.attrs:
if link.attrs['href'] not in pages:
#We have encountered a new page
newPage = link.attrs['href']
print(newPage)
pages.add(newPage)
getLinks(newPage)
getLinks("")
Run Code Online (Sandbox Code Playgroud)
错误是:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1319, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1049)>
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我也在练习scrapy,但一直都在解决问题:找不到命令:scrapy(我在网上尝试过各种解决方案,但都没有用......真的很令人沮丧)
我已经安装了 Anaconda 并且在尝试通过 Jupyter Notebooks 进行 API 调用时遇到了 SSL 问题:
import requests
import certifi
r = requests.get('https://github.com/')
print(r)
Run Code Online (Sandbox Code Playgroud)
这首先产生了 SSL 连接错误。经过广泛的搜索和我们 IT 部门的帮助,我可以解决这个问题。这里的解决方案是将公司根证书添加到 certifi 证书存储中。
现在对于其他请求,不幸的是我仍然遇到同样的问题。使用 google2pandas 包调用 Google Analytics API 的示例代码:
from google2pandas import *
query = {
'reportRequests': [{
'viewId' : 37616054,
'dateRanges': [{
'startDate' : '8daysAgo',
'endDate' : 'today'}],
'dimensions' : [
{'name' : 'ga:date'},
{'name' : 'ga:pagePath'},
{'name' : 'ga:browser'}],
'metrics' : [
{'expression' : 'ga:pageviews'}],
'dimensionFilterClauses' : [{
'operator' : 'AND',
'filters' : [
{'dimensionName' …Run Code Online (Sandbox Code Playgroud)