Python:使用 url 从谷歌驱动器下载文件 [英] Python: download files from google drive using url

查看:71
本文介绍了Python:使用 url 从谷歌驱动器下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从谷歌驱动器下载文件,但我只有驱动器的 URL.

I am trying to download files from google drive and all I have is the drive's URL.

我读过关于 google API 的一些drive_serviceMedioIO,这也需要一些凭据(主要是 JSON file/OAuth).但我不知道它是如何工作的.

I have read about google API that talks about some drive_service and MedioIO, which also requires some credentials( mainly JSON file/OAuth). But I am unable to get any idea about how it is working.

另外,尝试了 urllib2.urlretrieve,但我的情况是从驱动器中获取文件.也试过 wget 但没有用.

Also, tried urllib2.urlretrieve, but my case is to get files from the drive. Tried wget too but no use.

尝试了 PyDrive 库.它有很好的驱动上传功能,但没有下载选项.

Tried PyDrive library. It has good upload functions to drive but no download options.

任何帮助将不胜感激.谢谢.

Any help will be appreciated. Thanks.

推荐答案

如果驱动器的 url"是指 Google 云端硬盘上文件的可共享链接,那么以下内容可能会有所帮助:

If by "drive's url" you mean the shareable link of a file on Google Drive, then the following might help:

import requests

def download_file_from_google_drive(id, destination):
    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)    

def get_confirm_token(response):
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            return value

    return None

def save_response_content(response, destination):
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

if __name__ == "__main__":
    file_id = 'TAKE ID FROM SHAREABLE LINK'
    destination = 'DESTINATION FILE ON YOUR DISK'
    download_file_from_google_drive(file_id, destination)

截取的文件不使用 pydrive,也没有使用 Google Drive SDK.它使用 requests 模块(不知何故,它是 urllib2 的替代品).

The snipped does not use pydrive, nor the Google Drive SDK, though. It uses the requests module (which is, somehow, an alternative to urllib2).

从 Google Drive 下载大文件时,单个 GET 请求是不够的.需要第二个 - 请参阅来自谷歌驱动器的 wget/curl 大文件.

When downloading large files from Google Drive, a single GET request is not sufficient. A second one is needed - see wget/curl large file from google drive.

这篇关于Python:使用 url 从谷歌驱动器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆