Auscj 2024-07-16 22:15 采纳率: 0%
浏览 337

<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)>
捣鼓半天没有解决,这是什么问题呢?

img

img

  • 写回答

5条回答 默认 最新

  • GISer Liu 2024-07-16 22:25
    关注

    该回答引用自GPT-3.5, 由博主 GISer Liu 编写:

    问题分析

    用户在使用 pubchempy 库进行调用时遇到了 urlopen error TLS/SSL connection has been closed (EOF) (_ssl.c:1133) 的错误。这个错误通常与 SSL/TLS 连接的异常关闭有关,可能是由于以下几个原因导致的:

    1. Python 版本与 SSL 库版本不兼容。
    2. 系统 SSL 库存在问题。
    3. 网络环境不稳定或存在防火墙干扰。
    4. pubchempy 库本身的问题。

    解决方案

    1. 检查 Python 版本和 SSL 库版本

    首先,确保你使用的 Python 版本与 SSL 库版本兼容。可以通过以下命令查看 Python 版本:

    python --version
    

    然后,检查系统 SSL 库版本:

    openssl version
    

    如果版本不兼容,考虑升级 Python 或 OpenSSL 库。

    2. 更新 pubchempy

    确保 pubchempy 库是最新版本,可以通过以下命令更新:

    pip install --upgrade pubchempy
    

    3. 检查网络环境和防火墙设置

    确保网络环境稳定,并且没有防火墙阻止了 SSL 连接。可以尝试在不同的网络环境下运行代码,看是否能解决问题。

    4. 使用代理或 VPN

    如果网络环境受限,可以尝试使用代理或 VPN 来访问外部资源。

    5. 修改代码以捕获异常

    在代码中添加异常捕获,以便更好地调试和处理错误。以下是一个示例代码:

    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}")
    

    6. 使用 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。希望这些方法能帮助你解决问题。

    如果该回答解决了您的问题,请采纳!如果没有,请私信联系或评论您的疑惑

    评论

报告相同问题?

问题事件

  • 创建了问题 7月16日