Skip to main content
 首页 » 编程设计

python之使用 Python Gspread 访问 Google Drive 电子表格

2025年05月04日17bluestorm

我刚开始使用 Gspread 并试图访问我的 google 驱动器中的一个 google docs 电子表格。我按照说明转到 Google API 控制台并创建了一个 JSON 文件。当我运行这段代码时,我没有收到任何错误:

import gspread 
import json 
from oauth2client.client import SignedJwtAssertionCredentials 
 
json_key = json.load(open("mwsSearch-b3d5d5d9c956.json")) 
scope = ["https://spreadsheets.google.com/feeds"] 
credentials = SignedJwtAssertionCredentials(json_key['client_email'],  bytes(json_key['private_key'], 'utf-8'), scope=scope) 
gc = gspread.authorize(credentials) 

我的下一步是尝试打开一个谷歌电子表格。我在我的 Google Drive 的主文件夹中创建了一个名为“Mike”的电子表格,但我试图通过以下方式访问它:

gc.open_by_url("https://docs.google.com/spreadsheets/d/1HH7BKsnB2Rd5rlAr7S2H3avUtO4GkqeWrXJfYKKooNA/edit#gid=0") 
gc.open("Mike") 
gc.open_by_key("1HH7BKsnB2Rd5rlAr7S2H3avUtO4GkqeWrXJfYKKooNA") 

这三个都返回相同的错误:

gspread.exceptions.SpreadsheetNotFound 

我在想,也许 api 访问是通过项目链接到另一个云存储,而不是我个人的谷歌驱动器,这就是它不访问它的原因。在这方面有更多经验的人能否指出我做错事的正确方向。感谢所有帮助。谢谢。

请您参考如下方法:

您需要将使用 JSON key 创建的电子邮件添加到您要访问的电子表格中。它将类似于 9876.....@developer.gserviceaccount.com。您会在 JSON 文件和凭证页面中找到它作为“客户端电子邮件”。