You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python创建Google Spreadsheet时遇SSL证书验证失败问题求助

错误原因分析

这个SSL: CERTIFICATE_VERIFY_FAILED错误核心是Python环境无法验证Google OAuth服务器的SSL证书,常见触发场景:

  • 本地Python环境缺少根证书,或证书存储路径配置异常
  • 处于企业/学校代理环境下,代理拦截HTTPS请求并替换证书,导致无法验证原始服务器证书
  • 系统时间与实际网络时间偏差过大,证书有效期校验失败
解决方法

方法1:更新并指定Python根证书

  • 先安装官方根证书包:
    pip install certifi
    
    再在代码开头添加配置,强制使用certifi提供的证书:
    import certifi
    import os
    os.environ['SSL_CERT_FILE'] = certifi.where()
    
    # 后续原有代码保持不变
    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    
    scope = ['https://www.googleapis.com/auth/spreadsheets',
             "https://www.googleapis.com/auth/drive"]
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
    client = gspread.authorize(credentials)
    
    sheet = client.create("Test")
    

方法2:临时跳过SSL验证(仅测试环境用,不推荐生产)

通过自定义SSL上下文禁用证书验证,注意这会降低请求安全性:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import ssl

scope = ['https://www.googleapis.com/auth/spreadsheets',
         "https://www.googleapis.com/auth/drive"]

# 创建不验证SSL的上下文
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

credentials = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
# 传入自定义上下文初始化客户端
client = gspread.authorize(credentials, http=gspread.http_client.Http(context=ctx))

sheet = client.create("Test")

方法3:代理环境下配置代理证书

如果是代理拦截导致的问题,找到代理提供的CA证书文件(通常为.pem格式),在代码中指定证书路径:

import os
# 替换为你的代理CA证书实际路径
os.environ['REQUESTS_CA_BUNDLE'] = "/path/to/proxy-ca-cert.pem"

# 后续原有代码保持不变
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://www.googleapis.com/auth/spreadsheets',
         "https://www.googleapis.com/auth/drive"]

credentials = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(credentials)

sheet = client.create("Test")

也可以将代理证书导入系统根证书存储(具体操作根据Windows/macOS/Linux系统不同调整)。

方法4:校准系统时间

检查本地系统时间是否与网络时间一致,若偏差超过证书有效期范围,手动同步系统时间即可。


内容的提问来源于stack exchange,提问作者Diana Bugrimova

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:42:17