【发布时间】:2017-02-12 17:17:08
【问题描述】:
我目前正在使用此 stackoverflow 中的 session.get() 代码。当我保存驱动器文件时,它们没有文件类型后缀,所以我必须根据文件类型手动添加一个才能打开它。有没有办法可以解析块并获取文件类型变量,甚至可以通过十六进制代码搜索?更好的方法?
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
【问题讨论】: