Python:如何查找谷歌驱动器文件类型?

时间:2017-02-12 17:17:09

标签: python drive

我目前正在使用此stackoverflow中找到的session.get()代码。当我保存驱动器文件时,它们没有文件类型后缀,所以我必须手动添加一个文件类型以打开它。有没有办法可以解析块并获取filetype变量,甚至可以通过hexcode搜索?更好的方法?

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

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)

来源:Python: download files from google drive using url 来自@ user6770522

1 个答案:

答案 0 :(得分:0)

我使用了beatifulSoup和findAll来获取'title'标签。然后通过os path join将其应用到目标。

for filename in soup.findAll('title'):
    link = filename.string
    filename = link.replace(' - Google Drive','')
    destination = os.path.join(dir,filename)
    file_path = os.path.join(year_name, destination)
    drive_pull.download_file_from_google_drive(url_id, file_path)