命令行下载 google drive 文件

Posted by Chevy Blog on April 15, 2025

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

中小型文件 - 使用 gdown

安装 gdown

pip install gdown

获取 Google drive 文件(不能是文件夹)的ID

复制到的链接大概长下面这个样子,其中加粗的部分就是文件的ID
https://drive.google.com/file/d/12LhpGHvGu4wIgXrONspNKqfGFpTfr0-p/view?usp=drive_link

在 Python 中运行(注意下面的url和上面的不太一样)

>>> import gdown
>>> url = 'https://drive.google.com/uc?id=12LhpGHvGu4wIgXrONspNKqfGFpTfr0-p'
>>> output = 'file_name.txt'
>>> gdown.download(url, output, quiet=False)

这个方法对中小型文件可行,但对过大的文件(以上图中 40GB 的文件为例,文件ID1CDuzEbjK1hPbMItoJwrLIMgK25FSRM6_),会报下面的错

Access denied with the following error:

        Too many users have viewed or downloaded this file recently. Please
        try accessing the file again later. If the file you are trying to
        access is particularly large or is shared with many people, it may
        take up to 24 hours to be able to view or download the file. If you
        still can't access a file after 24 hours, contact your domain
        administrator.

You may still be able to access the file from the browser:

         https://drive.google.com/uc?id=1CDuzEbjK1hPbMItoJwrLIMgK25FSRM6_

这时,就需要使用 Token 和命令行下载(以下内容参考自 stackoverflow)。

大型文件 - 命令行

  • 进入 https://developers.google.com/oauthplayground/

  • 找到这一条并点击,然后点下面的 Authorize APIs

  • 再点击出现的Exchange authorization code for tokens

  • 复制生成的 Access Toekn

  • 在终端运行(注意,下面的ACCESS_TOKEN要换成刚才复制的,FILE_ID改成要下载的文件IDFILE_NAME改成要保存的文件名)

curl -H "Authorization: Bearer ACCESS_TOKEN" https://www.googleapis.com/drive/v3/files/FILE_ID?alt=media -o FILE_NAME

然后就开始漫长的传输了。