错误具体内容:
requests.exceptions.SSLError: HTTPSConnectionPool(host=‘api.github.com’, port=443): Max retries exceeded with url: /search/repositories?q=language:python&sort=stars (Caused by SSLError(SSLError(“bad handshake: SysCallError(10054, ‘WSAECONNRESET’)”)))
错误案例:
在运行以下一段代码时发生错误,具体报错内容简要在上方,可先行复制此段代码运行尝试,体验。
import requests
#执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:",r.status_code)
#将API响应存储在一个变量中
response_dict = r.json()
#处理结果
print(response_dict)
print("Total repositories:",response_dict['total_count'])
#探索有关仓库的信息
repo_dicts = response_dict['items']
print("Repositories returned:",len(repo_dicts))
#研究第一个仓库
repo_dict = repo_dicts[0]
print("\nSelected information about first repository:")
print('Name:',repo_dict['name'])
print('Owner:',repo_dict['owner']['login'])
print('Stars:',repo_dict['stargazers_count'])
print('Repository:',repo_dict['html_url'])
print('Created:',repo_dict['created_at'])
print('Updated:',repo_dict['updated_at'])
print('Description:',repo_dict['description'])
解决办法
经过搜索解决办法以及自己的摸索,大概找出了解决办法,如有不足之处,欢迎指正,不胜感激。
首先声明,解决办法参考自网页:https://blog.youkuaiyun.com/zahuopuboss/article/details/52964809
https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl
Method1:忽视警告(虽然您可以禁用证书验证,但强烈建议您保留它。因此不介绍此方法,如有需要,自行搜索)
Method2:安装以下三个包:
pip install cryptography
pip install pyOpenSSL
pip install certifi
通过使用以下命令与certlib和urllib3一起安装secure
pip install urllib3[secure]
原代码的基础上加上以下代码:
import certifi
import urllib3
http = urllib3.PoolManager(cert_reqs = 'CERT_REQUIRED', ca_certs = certifi.where())
问题到此为止已经解决。
注:笔者由于没有学过计算机网络相关课程,在学习python的过程中很多问题依然被保留,如果有感兴趣的朋友,欢迎交流。