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

Python调用Google Drive下载文件报错问题求助

问题分析与解决方案

问题根源

Google Drive近期调整了网页端的下载验证流程,原来用于确认下载的download_warning cookie已不再作为核心凭证,导致你的代码无法获取有效验证token,进而中断下载流程。

方案一:适配新验证逻辑(修复现有代码)

当前Google Drive对需确认的下载请求,会在响应HTML中返回confirm参数而非通过cookie传递。你可以修改get_confirm_token函数,从响应内容中提取验证token,同时保留原cookie检查以兼容特殊情况:

def get_confirm_token(response):
    # 从响应HTML中提取confirm验证参数
    import re
    match = re.search(r'confirm=([a-zA-Z0-9_-]+)', response.text)
    if match:
        return match.group(1)
    # 保留原cookie检查逻辑,兼容旧场景
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            return value
    return None

另外,在创建请求session后添加浏览器UA头,避免被Google的反爬机制拦截:

session = requests.Session()
# 添加模拟浏览器请求头
session.headers.update({
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
})

方案二:使用Google Drive API直接下载(长期稳定)

既然你已经通过OAuth2获取了Drive服务权限,直接调用官方API下载是最可靠的方案,无需依赖网页端不稳定的验证逻辑。修改相关函数如下:

替换下载函数

def download_file_from_google_drive(service, file_id, destination):
    # 发起API下载请求
    request = service.files().get_media(fileId=file_id)
    # 获取文件元数据(名称、大小)
    file_metadata = service.files().get(fileId=file_id).execute()
    file_size = int(file_metadata.get('size', 0))
    filename = file_metadata.get('name')
    
    CHUNK_SIZE = 32768
    progress = tqdm(total=file_size, unit="Byte", unit_scale=True, unit_divisor=1024, desc=f"Downloading {filename}")
    
    with open(destination, 'wb') as f:
        downloader = request.execute()
        f.write(downloader)
        progress.update(len(downloader))
    progress.close()

更新调用逻辑

def download_file(f_name):
    service = get_gdrive_service()
    filename = f_name
    search_result = search(service, query=f"name='{filename}'")
    file_id = search_result[0][0]
    # 传递service对象到下载函数
    download_file_from_google_drive(service, file_id, filename)

注意事项

  • 方案一属于模拟网页请求的非官方方式,后续Google若再次调整验证逻辑,可能需要再次适配。
  • 方案二基于官方API,你的现有权限范围(SCOPES)已满足下载要求,能长期稳定运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:20:51