2016-07-21 71 views
3

Googleドライブからファイルをダウンロードしようとしていますが、ドライブのURLがあります。Python:URLを使用してGoogleドライブからファイルをダウンロード

私はいくつかの資格情報(主にjsonファイル/ oauth)を必要とするいくつかのdrive_serviceとMedioIOについて語っているgoogle apiについて読んでいます。しかし、私はどのように働いているのか分からない。

また、urllib2 urlretrieveを試しましたが、私の場合はドライブからファイルを取得します。試してみました。

試したpydriveライブラリ。ドライブには良いアップロード機能がありますが、ダウンロードオプションはありません。

ご協力いただければ幸いです。おかげさまで

答えて

1

PyDriveは、GetContentFile()のファイルをダウンロードできます。関数の文書hereがあります。

以下の例を参照してください:このコード

# 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'. 

は、この上のドキュメントがherehereを見つけることができ、あなたが認証さ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) 

情報はhereを発見し、settings.yaml(例:here)を書き込む必要することができますが、認証の詳細を保存するに。

+1

あなたの答えは、 –

+0

最初のリンク壊れ:( – Joe

+0

@Joeは、リンクを固定! –

6

「ドライブの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、またGoogleドライブを使用していませんしかし、SDK。これはrequestsモジュールを使用します(何とかして、urllib2の代替)。

Googleドライブから大きなファイルをダウンロードする場合、1回のGETリクエストでは不十分です。もう1つは必要です - wget/curl large file from google driveを参照してください。

+0

作品、良い仕事がより興味深いものです – United121

0

これはまた、上記

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

を説明してきたこれは、独自のサーバーを作成し、あまりにもこれは

1

は、多くの同様のニーズを持っていたファイルをダウンロード

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

を認証するの汚い仕事を私は、上記の@ user115202のスニペットから始まる特別なクラスGoogleDriveDownloaderを作った。ソースコードhereがあります。

またピップを通してそれをインストールすることができます。

pip install googledrivedownloader 

次に使用量は同じくらい簡単です:Googleドライブで共有アーカイブをダウンロードします

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) 

このスニペット。この場合、1iytA1n2z4go3uVCwE__vIKouTKyIDjEqは、Googleドライブから取得した共有可能なリンクのIDです。

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が指定されたファイルを指定されたダウンロードフォルダにダウンロードします。今質問は残っていますが、file_idを取得する方法は? id =でURLを分割するだけで、file_idを取得できます。

file_id = url.split("id=")[1] 
関連する問題