【问题标题】:How can we read from Google Sheets into a DF in Python?我们如何从 Google 表格中读取 Python 中的 DF?
【发布时间】:2020-03-09 02:16:54
【问题描述】:

我正在运行这段代码(完全相同)。

import gspread
from oauth2client.service_account import ServiceAccountCredentials


# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("Sheet1").sheet1

# Extract and print all of the values
list_of_hashes = sheet.get_all_records()
print(list_of_hashes)

我不完全确定这条线是否正确:

scope = ['https://spreadsheets.google.com/feeds']

无论如何,我按照此链接中的说明进行操作。

https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html

我点击了“我的项目”>“服务帐户”>“启用”。我下载了 JSON 文件,将其命名为“client_secret.json”并将其放在此目录中:“C:\Users\ryans\client_secret.json”。最后,我打开 json 文件,在 client_secret.json 中获取“client_email”并将其放入“共享”并点击“保存”按钮。现在,当我运行上面的脚本时,我收到以下错误消息:

Traceback (most recent call last):

  File "<ipython-input-20-870ca6cceea6>", line 12, in <module>
    sheet = client.open("Sheet1").sheet1

  File "C:\Users\ryans\Anaconda3\lib\site-packages\gspread\client.py", line 123, in open
    self.list_spreadsheet_files()

  File "C:\Users\ryans\Anaconda3\lib\site-packages\gspread\client.py", line 96, in list_spreadsheet_files
    res = self.request('get', url, params=params).json()

  File "C:\Users\ryans\Anaconda3\lib\site-packages\gspread\client.py", line 79, in request
    raise APIError(response)

APIError: {'errors': [{'domain': 'global', 'reason': 'insufficientPermissions', 'message': 'Insufficient Permission: Request had insufficient authentication scopes.'}], 'code': 403, 'message': 'Insufficient Permission: Request had insufficient authentication scopes.'}

我不确定这里出了什么问题。会不会是权限问题?

更新

我添加了这一行:

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

我的 Google 表格如下所示:

现在,我将代码更改为:

import os
import gspread
from oauth2client.service_account import ServiceAccountCredentials

# make sure the 'client_secret.json' is getting picked up...
os.getcwd()

# use creds to create a client to interact with the Google Drive API
scope = ['https://docs.google.com/spreadsheets/d/1PBB1eJ7zbcLyj7vsdrB8nEyZ9Ri0Nds8M2yFB0zEN1Q/edit#gid=0']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("Sheet1").sheet1

# Extract and print all of the values
list_of_hashes = sheet.get_all_records()
print(list_of_hashes)

当我尝试运行该脚本时,我收到此错误消息。

Traceback (most recent call last):

  File "<ipython-input-34-e695bcd89439>", line 10, in <module>
    client = gspread.authorize(creds)

  File "C:\Users\ryans\Anaconda3\lib\site-packages\gspread\__init__.py", line 38, in authorize
    client.login()

  File "C:\Users\ryans\Anaconda3\lib\site-packages\gspread\client.py", line 51, in login
    self.auth.refresh(http)

  File "C:\Users\ryans\Anaconda3\lib\site-packages\oauth2client\client.py", line 545, in refresh
    self._refresh(http)

  File "C:\Users\ryans\Anaconda3\lib\site-packages\oauth2client\client.py", line 749, in _refresh
    self._do_refresh_request(http)

  File "C:\Users\ryans\Anaconda3\lib\site-packages\oauth2client\client.py", line 819, in _do_refresh_request
    raise HttpAccessTokenRefreshError(error_msg, status=resp.status)

HttpAccessTokenRefreshError: invalid_scope: Invalid oauth scope or ID token audience provided.

我的“Google Drive API”和“Google Sheets API”都已启用。我按照下面链接中列出的 7 个步骤进行操作。

https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html

最后,我点击了 Google 表格页面上的“分享”。尽管如此,我还是遇到了这个奇怪的错误,如上所述。

注意:这是我的 Google 表格的图片。

【问题讨论】:

    标签: python python-3.x google-sheets google-sheets-api gspread


    【解决方案1】:

    这个答案怎么样?请认为这只是几个可能的答案之一。

    问题及解决方案:

    看到gspread的脚本,好像是在运行open("Sheet1")的时候,使用了Drive API的files.list方法。 Ref 在您的脚本中,只有 https://spreadsheets.google.com/feeds 用于范围。我认为这样会出现insufficientPermissions 的错误。为了避免这种情况,下面的修改如何?

    修改脚本:

    从:
    scope = ['https://spreadsheets.google.com/feeds']
    
    到:
    scope = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive.readonly']
    
    • https://spreadsheets.google.com/feeds 适用于 Sheets API v3。 Sheets v3 API 于 2020 年 9 月 30 日关闭。所以在这种情况下,我建议使用 https://www.googleapis.com/auth/spreadsheets 作为使用 Sheets API 的范围。此外,gspread 使用 Sheets API v4。

    注意:

    • 如果您想使用修改文件元数据的方法,请使用https://www.googleapis.com/auth/drive的范围,而不是https://www.googleapis.com/auth/drive.readonly

    参考资料:

    【讨论】:

    • 嘿,Tanaike。我刚刚更新了我原来的帖子,从“更新:”开始。您对我如何使这项工作有任何其他想法吗?谢谢。
    • @ASH 感谢您的回复。我带来的不便表示歉意。当我看到您更新的问题时,范围使用scope = ['https://docs.google.com/spreadsheets/d/1PBB1eJ7zbcLyj7vsdrB8nEyZ9Ri0Nds8M2yFB0zEN1Q/edit#gid=0']。此值不是正确的范围。那么修改成scope = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive.readonly']怎么样?
    • 我刚刚尝试了您的建议。现在,我得到了这个: Traceback(最近一次通话最后一次):文件“”,第 16 行,在 sheet = client.open('Sheet1').sheet1 File "C :\Users\ryans\Anaconda3\lib\site-packages\gspread\client.py",第 131 行,公开提出 SpreadsheetNotFound SpreadsheetNotFound
    • @ASH 感谢您的回复。对于给您带来的不便,我深表歉意。从您的回复中,我可以确认范围和授权的问题已经解决。关于新的错误信息,这意味着没有找到Sheet1 的电子表格名称。所以我认为你可能误解了Sheet1sheet = client.open("Sheet1").sheet1。但是,不幸的是,我不确定您要使用的 电子表格标题,它是电子表格文件名。所以请再次确认电子表格标题并设置### of sheet = client.open("###").sheet1
    • 您的解决方案绝对帮助我朝着正确的方向前进!我刚刚对你原来的帖子投了赞成票!!
    【解决方案2】:

    (代表问题作者发布解决方案以将其从问题帖子中移出)

    我终于弄清楚了这是如何工作的。在名为“statup_funding.json”的文件中,您必须获取生成的电子邮件,然后单击电子表格上的“共享”按钮,然后将电子邮件地址粘贴到打开的窗口中。然后,一切都按预期进行。

    这是我现在工作代码的最终版本。

    import gspread
    #Service client credential from oauth2client
    from oauth2client.service_account import ServiceAccountCredentials
    # Print nicely
    import pprint
    #Create scope
    scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
    #create some credential using that scope and content of startup_funding.json
    creds = ServiceAccountCredentials.from_json_keyfile_name('startup_funding.json',scope)
    #create gspread authorize using that credential
    client = gspread.authorize(creds)
    #Now will can access our google sheets we call client.open on StartupName
    sheet = client.open('Test_Sheet').sheet1
    pp = pprint.PrettyPrinter()
    results = sheet.get_all_records()
    results
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 2018-07-04
      • 2013-01-21
      相关资源
      最近更新 更多