You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

授权Google Drive服务账号将pandas DataFrame写入Google Sheets遇403权限错误求助

问题原因

  1. 认证权限范围不足:你当前配置的scope仅授权访问Google Sheets接口,未授权Drive API的文件操作权限,所以调用drive.files.create时触发403权限错误。
  2. 文件夹参数格式错误:Drive API的parents字段需要传入目标文件夹的唯一ID,而非Colab挂载的本地文件路径,你当前填写的路径格式不符合接口要求。
  3. 额外注意:你需要确认创建服务账号的Google Cloud项目已同时启用Google Sheets API和Google Drive API,未启用也会触发权限类报错。

修复步骤

  • 第一步:补充认证scope,覆盖Sheets和Drive两类接口的操作权限
  • 第二步:获取目标文件夹ID:打开你Google Drive中/project/scrapers/csv_output文件夹,复制浏览器地址栏中folders/后的字符串,即为文件夹ID,替换代码中的对应变量

修正后完整代码

import os
import gspread
import pandas as pd
from google.colab import drive
from oauth2client.service_account import ServiceAccountCredentials
from apiclient import discovery

# 挂载Google Drive
drive.mount("/content/gdrive")

# 修正后的认证scope
scope = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]
# 替换为你实际的密钥存储路径
filepath = '/content/gdrive/My Drive/project/scrapers/utils/auth_key.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(filepath, scope)
gc = gspread.authorize(credentials)

# 配置参数
title = 'test'
# 替换为你自己的目标文件夹ID
dest_folder_id = '替换为你获取的文件夹ID字符串'

# 创建Google Sheet到指定文件夹
drive_service = discovery.build('drive', 'v3', credentials=credentials)
file_metadata = {
    'name': title,
    'mimeType': 'application/vnd.google-apps.spreadsheet',
    'parents': [dest_folder_id]
}
created_file = drive_service.files().create(body=file_metadata, fields='id').execute()
sheet_id = created_file.get('id')

# 写入pandas dataframe示例(取消注释即可使用)
# df = 你的pandas dataframe变量
# workbook = gc.open_by_key(sheet_id)
# worksheet = workbook.sheet1
# worksheet.update([df.columns.values.tolist()] + df.values.tolist())

内容的提问来源于stack exchange,提问作者roody

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 02:12:10