如何使用 Python 请求模块访问谷歌表的数据

1 python python-requests

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

当我使用时,我只能报废登录页面的数据:

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

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

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

小智 7

假设您已经通过遵循 OAuth 2 身份验证过程获得了访问令牌,您可以使用我编写的以下函数将数据从您的谷歌表中提取到熊猫数据帧中。

此方法利用了 python requests 模块并避免了 Google 推荐的包。

import pandas as pd
import numpy as np
import requests

def get_google_sheet_df(headers: dict, google_sheet_id: str, sheet_name: str, _range: str):
    """_range is in A1 notation (i.e. A:I gives all rows for columns A to I)"""

    url = f'https://sheets.googleapis.com/v4/spreadsheets/{google_sheet_id}/values/{sheet_name}!{_range}'
    r = requests.get(url, headers=headers)
    values = r.json()['values']
    df = pd.DataFrame(values[1:])
    df.columns = values[0]
    df = df.apply(lambda x: x.str.strip()).replace('', np.nan)
    return df

headers = {'authorization': f'Bearer {access_token}',
           'Content-Type': 'application/vnd.api+json'}

google_sheet_id = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
sheet_name = 'Class Data'
sample_range = 'A:F'

df = get_google_sheet_df(headers, google_sheet_id, sheet_name, sample_range)
Run Code Online (Sandbox Code Playgroud)

您可以在本示例中提供的 google_sheet_id 上对其进行测试,您只需要访问令牌即可。

谷歌表拉示例