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

使用OAuth2与gspread操作Google Sheets时遇invalid_scope错误求助

解决gspread + OAuth2操作Google Sheets的invalid_scope错误

嘿,我一眼就看出问题出在哪了——你用的https://spreadsheets.google.com/feeds是旧版Google Data API的作用域,现在gspread依赖的是Google Sheets API v4,这个旧作用域早就失效了,所以不管你改成列表还是空格分隔字符串,都会报invalid_scope错误。

正确的作用域清单

根据你需要的权限,选对应的合法作用域就好:

  • 只读表格权限:https://www.googleapis.com/auth/spreadsheets.readonly
  • 全读写表格权限:https://www.googleapis.com/auth/spreadsheets
  • 如果需要通过文件名查找表格(用到Google Drive),再加一个:https://www.googleapis.com/auth/drive(或者更严格的https://www.googleapis.com/auth/drive.file,只能访问服务账号创建的文件)

修改后的完整代码示例

我给你写了一份可以直接用的代码,记得替换成你的密钥文件路径和表格名称:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 这里用的是全读写+Drive访问权限,你可以按需删减
scope = [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive"
]

# 加载你的服务账号密钥JSON文件
creds = ServiceAccountCredentials.from_json_keyfile_name('你的服务账号密钥文件路径.json', scope)

# 授权并创建gspread客户端
client = gspread.authorize(creds)

# 打开目标表格(可以用表格名称或者表格ID)
sheet = client.open("你的表格名称").sheet1

# 测试读取表格数据,验证是否成功
all_records = sheet.get_all_records()
print(all_records)

额外注意事项

  • 别忘了在Google Cloud Console里给你的服务账号启用Google Sheets API和Google Drive API(如果用到Drive作用域的话)
  • 一定要把服务账号的client_email(在密钥JSON里能找到)添加到目标Google Sheet的共享列表里,给它对应的读写权限,不然会报权限不足的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:41:44