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

如何从Google Drive指定文件夹下载文件并替换Heroku现有文件

解决Google Drive文件批量下载与替换问题

一、使用PyDrive实现完整流程

1. 准备工作

  • 完成Google Drive API配置,获取client_secrets.json文件(在Google Cloud控制台创建项目、启用Drive API、生成OAuth客户端ID)
  • 安装PyDrive依赖:pip install PyDrive

2. 完整代码实现

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import os

# 初始化本地存储目录,不存在则创建
LOCAL_DIR = "./project_csv"
os.makedirs(LOCAL_DIR, exist_ok=True)

# 1. 登录Google Drive
gauth = GoogleAuth()
# 加载本地凭证,避免重复授权;Heroku部署可将凭证内容存入环境变量
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
    # 首次运行需手动完成网页授权
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    gauth.Refresh()
else:
    gauth.Authorize()
gauth.SaveCredentialsFile("mycreds.txt")
drive = GoogleDrive(gauth)

# 2. 定位目标文件夹:salescontrol7/csv
# 先查找salescontrol7文件夹
parent_folder = drive.ListFile({'q': "title='salescontrol7' and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()[0]
# 再查找其子文件夹csv
csv_folder = drive.ListFile({'q': f"'{parent_folder['id']}' in parents and title='csv' and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()[0]

# 3. 下载文件并覆盖本地旧文件
file_list = drive.ListFile({'q': f"'{csv_folder['id']}' in parents and trashed=false"}).GetList()
for file in file_list:
    local_file_path = os.path.join(LOCAL_DIR, file['title'])
    # 启用overwrite参数直接替换旧文件
    file.GetContentFile(local_file_path, overwrite=True)
    print(f"已完成文件替换: {local_file_path}")

核心说明

  • overwrite=True是实现直接替换的关键,无需手动删除本地原有文件
  • Heroku部署时,建议将mycreds.txt的内容存入环境变量,运行时再写入文件,避免凭证丢失

二、通过公开共享链接直接下载(无需登录)

如果目标文件夹已设置为公开可访问,可以跳过登录流程,直接解析共享链接下载文件。

1. 代码实现

import requests
import os
from bs4 import BeautifulSoup

# 公开文件夹共享链接
FOLDER_URL = "https://drive.google.com/drive/folders/1CuiRmfX2ORIzb62EM-L1x6UCm6t2uu4M?usp=sharing"
LOCAL_DIR = "./project_csv"
os.makedirs(LOCAL_DIR, exist_ok=True)

# 解析公开页面,提取文件信息与下载链接
response = requests.get(FOLDER_URL)
soup = BeautifulSoup(response.text, 'html.parser')
file_info_list = []

# 提取文件名称与ID,构造直接下载链接
for item in soup.find_all('div', class_='Q5txwe'):
    file_title = item.find('div', class_='q5txwe').text
    file_id = item.find('a')['href'].split('/')[-2]
    download_url = f"https://drive.google.com/uc?export=download&id={file_id}"
    file_info_list.append((file_title, download_url))

# 下载并覆盖本地文件
for title, url in file_info_list:
    local_path = os.path.join(LOCAL_DIR, title)
    with open(local_path, 'wb') as f:
        f.write(requests.get(url).content)
    print(f"已完成文件替换: {local_path}")

核心说明

  • 仅适用于公开共享的文件夹,若权限改为私有则无法使用
  • 依赖beautifulsoup4库,安装命令:pip install beautifulsoup4 requests
  • 若Google Drive页面结构更新,需调整HTML元素选择器以适配解析逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:39:22