调用pubchempy但是报错:<urlopen error TLS/SSL connection has been closed (EOF) (_ssl.c:1133)>
捣鼓半天没有解决,这是什么问题呢?


调用pubchempy但是报错:<urlopen error TLS/SSL connection has been closed (EOF) (_ssl.c:1133)>
捣鼓半天没有解决,这是什么问题呢?


该回答引用自GPT-3.5, 由博主 GISer Liu 编写:
用户在使用 pubchempy 库进行调用时遇到了 urlopen error TLS/SSL connection has been closed (EOF) (_ssl.c:1133) 的错误。这个错误通常与 SSL/TLS 连接的异常关闭有关,可能是由于以下几个原因导致的:
pubchempy 库本身的问题。首先,确保你使用的 Python 版本与 SSL 库版本兼容。可以通过以下命令查看 Python 版本:
python --version
然后,检查系统 SSL 库版本:
openssl version
如果版本不兼容,考虑升级 Python 或 OpenSSL 库。
pubchempy 库确保 pubchempy 库是最新版本,可以通过以下命令更新:
pip install --upgrade pubchempy
确保网络环境稳定,并且没有防火墙阻止了 SSL 连接。可以尝试在不同的网络环境下运行代码,看是否能解决问题。
如果网络环境受限,可以尝试使用代理或 VPN 来访问外部资源。
在代码中添加异常捕获,以便更好地调试和处理错误。以下是一个示例代码:
import pubchempy as pcp
import ssl
try:
# 尝试获取化合物信息
compound = pcp.get_compounds('aspirin', 'name')
print(compound)
except ssl.SSLEOFError as e:
print(f"SSL/TLS connection error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
requests 库替代 urllib如果问题依然存在,可以尝试使用 requests 库来替代 urllib,因为 requests 库对 SSL 连接的处理更为友好。以下是一个使用 requests 库的示例:
import requests
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/aspirin/JSON'
try:
response = requests.get(url)
if response.status_code == 200:
print(response.json())
else:
print(f"Request failed with status code: {response.status_code}")
except requests.exceptions.SSLError as e:
print(f"SSL/TLS connection error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
通过以上步骤,可以逐步排查和解决 urlopen error TLS/SSL connection has been closed (EOF) (_ssl.c:1133) 错误。首先确保 Python 和 SSL 库版本兼容,然后更新 pubchempy 库,检查网络环境和防火墙设置,使用代理或 VPN,修改代码以捕获异常,最后可以尝试使用 requests 库替代 urllib。希望这些方法能帮助你解决问题。
如果该回答解决了您的问题,请采纳!如果没有,请私信联系或评论您的疑惑