Created
January 4, 2018 02:02
-
-
Save joshtch/8e51c6d40b1e3205d1bb2eea18fb57ae to your computer and use it in GitHub Desktop.
Google Drive file downloader for Python, with progress bar with tqdm. Based on this SO answer https://stackoverflow.com/a/39225039/3175094
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
import requests | |
from tqdm import tqdm | |
import re | |
import os | |
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 = None | |
for key, value in response.cookies.items(): | |
if key.startswith('download_warning'): | |
token = value | |
break | |
if token: | |
params = { 'id' : id, 'confirm' : token } | |
response = session.get(URL, params = params, stream = True) | |
CHUNK_SIZE = 32*1024 | |
# TODO: this doesn't seem to work; there's no Content-Length value in header? | |
total_size = int(response.headers.get('content-length', 0)) | |
with tqdm(desc=destination, total=total_size, unit='B', unit_scale=True) as pbar: | |
with open(destination, 'wb') as f: | |
for chunk in response.iter_content(CHUNK_SIZE): | |
if chunk: | |
pbar.update(CHUNK_SIZE) | |
f.write(chunk) | |
if __name__ == '__main__': | |
import sys | |
if len(sys.argv) is not 3: | |
executable = os.path.basename(sys.argv[0]) | |
print 'Usage: [python] %s {DRIVE_FILE_ID_OR_URL} {DESTINATION_FILE_PATH}' % executable | |
else: | |
# TAKE ID FROM SHAREABLE LINK | |
if sys.argv[1].startswith('https://'): | |
file_id = re.match(r'[?&]id=([a-zA-Z0-9_-]+)').group(1) | |
else: | |
file_id = sys.argv[1] | |
# DESTINATION FILE ON YOUR DISK | |
destination = sys.argv[2] | |
download_file_from_google_drive(file_id, destination) |
There should be a way to ask Google's REST API from Python for the size
field of the file's metadata. I haven't tried using this, but maybe https://stackoverflow.com/a/44323217/4896937 has some insight?
It seems not work any more. https://drive.google.com/file/d/0B6eKvaijfFUDQUUwd21EckhUbWs/view this file will return port=443 Max retries exceed.
You can get the size of the file from the api by quering from the fileid the filesize.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I haven't found a reliable way of getting the file size. The response header from the server doesn't have a value for
Content-Length
, possibly because the data is chunked. If you know the size of the file you want to download, you can manually set thetotal_size
variable to get a proper progress bar.