AttributeError: module 'gspread' has no attribute 'open_by_key'

AttributeError: module 'gspread' has no attribute 'open_by_key'

我正在尝试使用 gspread 从 python 访问电子表格,但一直收到属性错误。

open_by_url()open() 也不起作用,它们给出了一个属性错误,并说 gspread 没有那个模块。我重新安装了 gspread v3.6.0 两次,但没有任何作用。打开电子表格的文档是 at the gspread docs.

您是否从 console.developers.google.com 获得了包含凭据的 json 文件?如果是这样,您可以使用:

from gspread import authorize
from oauth2client.service_account import ServiceAccountCredentials

scopes = ["https://spreadsheets.google.com/feeds",
                  "https://www.googleapis.com/auth/spreadsheets",
                  "https://www.googleapis.com/auth/drive",
                  "https://www.googleapis.com/auth/drive"]
cred = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scopes)
gclient = authorize(cred)
sheet = gclient.open(sheet_name).worksheet(page)

sheet_name 是传播的标题sheet,页面是底部 sheet 的名称。

确保您遵循 gspread 的身份验证 here. Once the auth is complete, you can verify it by using python's built in function dir

示例:

服务帐号:

import gspread    
gc = gspread.service_account()
print(dir(gc))

OAuth

import gspread
gc = gspread.oauth()
print(dir(gc))

您应该会看到该方法已打开并且 open_by_url

您可以使用服务帐户或 OAuth 来访问您的电子表格。

按照以下步骤操作:

服务帐号 - https://gspread.readthedocs.io/en/latest/oauth2.html#for-bots-using-service-account

OAuth - https://gspread.readthedocs.io/en/latest/oauth2.html#for-end-users-using-oauth-client-id