如何使用Python请求模块访问Google工作表的数据

问题描述 投票:0回答:2

我想访问Google文档或电子表格中的内容。我正在使用Google文档中点击“获取可共享链接”时生成的链接。

我只能在使用时删除登录页面的数据:

import requests 
r = requests.get("https://docs.google.com/spreadsheets/e/abcdef12345_sample/edit?usp=sharing", auth=('user', 'pass'));
print(r.content)

但我想废弃电子表格/文档中的内容。注意:我的帐户已启用MFA。

我怎样才能做到这一点?我应该使用除基本身份验证之外的任何其他类型的身份验证吗?

python python-requests
2个回答
0
投票

您可以使用Google表格API。

步骤是here

  1. 启用Google表格API
  2. 安装Google客户端库
  3. 创建一个名为quickstart.py的文件。确保更改SPREADSHEET_ID。要查找电子表格ID,请检查其网址。它是在/ d /之后。 https://docs.google.com/spreadsheets/d/spreadsheetId/edit#gid=sheetId from __future__ import print_function from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # If modifying these scopes, delete the file token.json. SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly' # The ID and range of a sample spreadsheet. SPREADSHEET_ID = 'spreadsheetId' RANGE_NAME = 'Class Data!A2:E' def main(): """Show basic usage of Sheets API. Print items in sheets. """ store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) # Call the Sheets API SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' RANGE_NAME = 'Class Data!A2:E' result = service.spreadsheets().values().get( spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) if not values: print('No data found.') else: print('Name, Major:') for row in values: # Print columns A and E, which correspond to indices 0 and 4. print('%s, %s' % (row[0], row[4])) if __name__ == '__main__': main()
  4. 运行quickstart.py
  5. 享受API!

-1
投票

有一个名为gspread的python库,使用pip install gspread 安装你还需要使用Google's developer console从Google获取OAuth2凭据。您需要的所有信息都在gspread文档中。

© www.soinside.com 2019 - 2024. All rights reserved.