2016-07-21 306 views
3

我想從谷歌驅動器下載文件,我所有的是驅動器的網址。Python:使用網址從谷歌驅動器下載文件

我已閱讀關於一些drive_service和MedioIO,這也需要一些憑據(主要是json文件/ oauth)的谷歌API。但我無法瞭解它的工作原理。

另外,嘗試urllib2 urlretrieve,但我的情況是從驅動器獲取文件。試過'wget',但沒用。

試過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'. 

此代碼假定你有一個認證drive對象,在這個文檔可以發現herehere

在此可以這樣判定一般情況下:

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

如果「驅動器的網址」你的意思是在谷歌雲端硬盤中的文件的分享的鏈接,那麼下面可能會有所幫助:

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。它使用requests模塊(這是一種替代urllib2)。

從Google Drive下載大文件時,單個GET請求是不夠的。第二個是必要的 - 見wget/curl large file from google drive

+0

工程,抓好 – United121

0

這也被如上所述,

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') 

此下載文件

1

有過類似的需求,許多次,我在上面的@ user115202的片段中開始了一個額外的簡單類GoogleDriveDownloader。你可以找到源代碼here

您也可以通過畫中畫安裝:

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) 

這段代碼會下載在谷歌驅動器共享的歸檔。在這種情況下,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] 
相關問題