服務器(終端)下載 Google Drive 上面的數據

##  服務器(終端)下載 Google Drive 上面的數據

之前在終端下載google drive上的數據都是先下載到本地,再上傳,發現太麻煩了,今天找到一種方法分享給大家,

可以去github上下載下載的python腳本:https://github.com/chentinghao/download_google_drive/blob/master/download_gdrive.py

因爲代碼比較短,我粘貼過來:

import requests

from tqdm import tqdm

def download_file_from_google_drive(id, 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:
            with tqdm(unit='B', unit_scale=True, unit_divisor=1024) as bar:
                for chunk in response.iter_content(CHUNK_SIZE):
                    if chunk:  # filter out keep-alive new chunks
                        f.write(chunk)
                        bar.update(CHUNK_SIZE)

    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)    


if __name__ == "__main__":
    import sys
    if len(sys.argv) is not 3:
        print("Usage: python google_drive.py drive_file_id destination_file_path")
    else:
        # TAKE ID FROM SHAREABLE LINK
        file_id = sys.argv[1]
        # DESTINATION FILE ON YOUR DISK
        destination = sys.argv[2]
        download_file_from_google_drive(file_id, destination)

然後可以直接運行這個腳本;

 

python download_gdrive.py GoogleFileID /path/xxxx.file

其中GoogleFileID 就是url中的id,/path/xxxx.file就是存放文件的位置和文件名,

獲取GoogleFileID如下:

單擊右鍵:

 

點擊“獲取共享鏈接”,

複製url,可以得到如下:

https://drive.google.com/open?id=1wp8h_9zzApMskUnQHYsrtvg-nGsQxj0d

那麼GoogleFileID就是id後面的那一串,也就是  1wp8h_9zzApMskUnQHYsrtvg-nGsQxj0d

那麼運行腳本就是:

python download_gdrive.py 1wp8h_9zzApMskUnQHYsrtvg-nGsQxj0d /path/download.file
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章