Python: downloading files from Google Drive using URL

I am trying to download files from a Google drive, and all I have is the URL of the drive.

I read about the google api that talks about some drive_service and MedioIO systems that also require some credentials (mostly json file / oauth). But I can’t understand how this works.

Also, I tried urllib2 urlretrieve, but my case is to get files from disk. Tried "wget" too, but didn't use it.

Tried the pydrive library. It has good download features, not boot options.

Any help would be appreciated. Thank.

+4
source share
5 answers

"drive url" Google , :

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, SDK Google . requests ( - urllib2).

Google GET . - wget/curl Google .

+6

PyDrive GetContentFile(). .

. :

# Initialize GoogleDriveFile instance with file id.
file_obj = drive.CreateFile({'id': '<your file ID here>'})
file_obj.GetContentFile('cats.png') # Download file as 'cats.png'.

, drive, .

:

from pydrive.auth import GoogleAuth

gauth = GoogleAuth()
# Create local webserver which automatically handles authentication.
gauth.LocalWebserverAuth()

# Create GoogleDrive instance with authenticated GoogleAuth instance.
drive = GoogleDrive(gauth)

settings.yaml (: ), .

+1

, GoogleDriveDownloader, @user115202 . .

pip:

pip install googledrivedownloader

, :

from google_drive_downloader import GoogleDriveDownloader as gdd

gdd.download_file_from_google_drive(file_id='1iytA1n2z4go3uVCwE__vIKouTKyIDjEq',
                                    dest_path='./data/mnist.zip',
                                    unzip=True)

, Google . 1iytA1n2z4go3uVCwE__vIKouTKyIDjEq , Google .

+1

,

   from pydrive.auth import GoogleAuth
   gauth = GoogleAuth()
   gauth.LocalWebserverAuth()
   drive = GoogleDrive(gauth)

,

   file_obj = drive.CreateFile({'id': '<Put the file ID here>'})
   file_obj.GetContentFile('Demo.txt') 

0
def download_tracking_file_by_id(file_id, download_dir):
    gauth = GoogleAuth(settings_file='../settings.yaml')
    # Try to load saved client credentials
    gauth.LoadCredentialsFile("../credentials.json")
    if gauth.credentials is None:
        # Authenticate if they're not there
        gauth.LocalWebserverAuth()
    elif gauth.access_token_expired:
        # Refresh them if expired
        gauth.Refresh()
    else:
        # Initialize the saved creds
        gauth.Authorize()
    # Save the current credentials to a file
    gauth.SaveCredentialsFile("../credentials.json")

    drive = GoogleDrive(gauth)

    logger.debug("Trying to download file_id " + str(file_id))
    file6 = drive.CreateFile({'id': file_id})
    file6.GetContentFile(download_dir+'mapmob.zip')
    zipfile.ZipFile(download_dir + 'test.zip').extractall(UNZIP_DIR)
    tracking_data_location = download_dir + 'test.json'
    return tracking_data_location

, file_id, . , _? url id =, file_id.

file_id = url.split("id=")[1]
0

Source: https://habr.com/ru/post/1648689/


All Articles