Python:使用 url 从 google 驱动器下载文件
Python: download files from google drive using url
我正在尝试从 google 驱动器下载文件,但我只有驱动器的 URL。
我读过关于 google API 的文章,其中谈到了一些 drive_service
和 MedioIO
,这也需要一些凭据(主要是 JSON file/OAuth
).但是我不知道它是如何工作的。
另外,尝试了 urllib2.urlretrieve
,但我的情况是从驱动器中获取文件。也试过 wget
但没有用。
尝试了 PyDrive
库。它有很好的驱动上传功能,但没有下载选项。
如有任何帮助,我们将不胜感激。
谢谢。
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
对象,可以在 here and here.
中找到相关文档
在一般情况下,这样做是这样的:
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 and involves writing a settings.yaml
(example: here),您可以在其中保存身份验证详细信息。
如果 "drive's url" 是指 可共享 link 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 Drive SDK。它使用 requests 模块(不知何故,它是 urllib2 的替代品)。
从 Google 驱动器下载大文件时,单个 GET 请求是不够的。需要第二个 - 参见 wget/curl large file from google drive.
这个上面也有介绍,
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')
这将下载文件
有过多次类似的需求,我从上面@user115202 的代码片段开始做了一个特别简单的 class GoogleDriveDownloader
。你可以找到源代码here.
也可以通过pip安装:
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)
此代码段将下载 Google 云端硬盘中共享的存档。在这种情况下,1iytA1n2z4go3uVCwE__vIKouTKyIDjEq
是从 Google 驱动器获得的可共享 link 的 ID。
# Importing [PyDrive][1] OAuth
from pydrive.auth import GoogleAuth
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?只需将 url 拆分为 id= 即可得到 file_id.
file_id = url.split("id=")[1]
您可以安装https://pypi.org/project/googleDriveFileDownloader/
pip install googleDriveFileDownloader
并下载文件,这里是下载示例代码
from googleDriveFileDownloader import googleDriveFileDownloader
a = googleDriveFileDownloader()
a.downloadFile("https://drive.google.com/uc?id=1O4x8rwGJAh8gRo8sjm0kuKFf6vCEm93G&export=download")
我推荐gdown包。
pip install gdown
分享你的一份link
https://drive.google.com/file/d/0B9P1L--7Wd2vNm9zMTJWOGxobkU/view?usp=sharing
并获取 ID - 例如。 1TLNdIufzwesDbyr_nVTR7Zrx9oRHLM_N 按下载按钮(在 link 处查找),然后在下面的 id 后换入。
import gdown
url = 'https://drive.google.com/uc?id=0B9P1L--7Wd2vNm9zMTJWOGxobkU'
output = '20150428_collected_images.tgz'
gdown.download(url, output, quiet=False)
一般来说,来自 Google 驱动器的共享文件的 URL 看起来像这样
https://drive.google.com/file/d/1HV6vf8pB-EYnjcJcH65eGZVMa2v2tcMh/view?usp=sharing
其中 1HV6vf8pB-EYnjcJcH65eGZVMa2v2tcMh
对应于文件 ID。
因此,您可以简单地创建一个函数来从 URL 中获取文件 ID,例如 url = https://drive.google.com/file/d/1HV6vf8pB-EYnjcJcH65eGZVMa2v2tcMh/view?usp=sharing
、
def url_to_id(url):
x = url.split("/")
return x[5]
打印 x 会得到
['https:', '', 'drive.google.com', 'file', 'd', '1HV6vf8pB-EYnjcJcH65eGZVMa2v2tcMh', 'view?usp=sharing']
因此,因为我们想要 return 第 6 个数组值,所以我们使用 x[5]
.
这是一个简单的方法,无需 third-party 库和服务帐户。
pip 安装 google-api-core
和 google-api-python-client
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google.oauth2 import service_account
import io
credz = {} #put json credentials her from service account or the like
# More info: https://cloud.google.com/docs/authentication
credentials = service_account.Credentials.from_service_account_info(credz)
drive_service = build('drive', 'v3', credentials=credentials)
file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
request = drive_service.files().get_media(fileId=file_id)
#fh = io.BytesIO() # this can be used to keep in memory
fh = io.FileIO('file.tar.gz', 'wb') # this can be used to write to disk
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download %d%%." % int(status.progress() * 100))
这个例子是基于一个类似于RayB的,但是将文件保存在内存中
并且更简单一些,您可以将其粘贴到 colab 中并且可以使用。
import googleapiclient.discovery
import oauth2client.client
from google.colab import auth
auth.authenticate_user()
def download_gdrive(id):
creds = oauth2client.client.GoogleCredentials.get_application_default()
service = googleapiclient.discovery.build('drive', 'v3', credentials=creds)
return service.files().get_media(fileId=id).execute()
a = download_gdrive("1F-yaQB8fdsfsdafm2l8WFjhEiYSHZrCcr")
我尝试使用 google Colaboratory:https://colab.research.google.com/
假设您的可分享 link 是 https://docs.google.com/spreadsheets/d/12hiI0NK7M0KEfscMfyBaLT9gxcZMleeu/edit?usp=sharing&ouid=102608702203033509854&rtpof=true&sd=true
你只需要 id 12hiI0NK7M0KEfscMfyBaLT9gxcZMleeu
单元格中的命令
!gdown 12hiI0NK7M0KEfscMfyBaLT9gxcZMleeu
运行 单元格,您会看到该文件已下载到 /content/Amazon_Reviews.xlsx
注意:应该知道如何使用 Google colab
我正在尝试从 google 驱动器下载文件,但我只有驱动器的 URL。
我读过关于 google API 的文章,其中谈到了一些 drive_service
和 MedioIO
,这也需要一些凭据(主要是 JSON file/OAuth
).但是我不知道它是如何工作的。
另外,尝试了 urllib2.urlretrieve
,但我的情况是从驱动器中获取文件。也试过 wget
但没有用。
尝试了 PyDrive
库。它有很好的驱动上传功能,但没有下载选项。
如有任何帮助,我们将不胜感激。 谢谢。
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
对象,可以在 here and here.
在一般情况下,这样做是这样的:
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 and involves writing a settings.yaml
(example: here),您可以在其中保存身份验证详细信息。
如果 "drive's url" 是指 可共享 link 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 Drive SDK。它使用 requests 模块(不知何故,它是 urllib2 的替代品)。
从 Google 驱动器下载大文件时,单个 GET 请求是不够的。需要第二个 - 参见 wget/curl large file from google drive.
这个上面也有介绍,
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')
这将下载文件
有过多次类似的需求,我从上面@user115202 的代码片段开始做了一个特别简单的 class GoogleDriveDownloader
。你可以找到源代码here.
也可以通过pip安装:
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)
此代码段将下载 Google 云端硬盘中共享的存档。在这种情况下,1iytA1n2z4go3uVCwE__vIKouTKyIDjEq
是从 Google 驱动器获得的可共享 link 的 ID。
# Importing [PyDrive][1] OAuth
from pydrive.auth import GoogleAuth
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?只需将 url 拆分为 id= 即可得到 file_id.
file_id = url.split("id=")[1]
您可以安装https://pypi.org/project/googleDriveFileDownloader/
pip install googleDriveFileDownloader
并下载文件,这里是下载示例代码
from googleDriveFileDownloader import googleDriveFileDownloader
a = googleDriveFileDownloader()
a.downloadFile("https://drive.google.com/uc?id=1O4x8rwGJAh8gRo8sjm0kuKFf6vCEm93G&export=download")
我推荐gdown包。
pip install gdown
分享你的一份link
https://drive.google.com/file/d/0B9P1L--7Wd2vNm9zMTJWOGxobkU/view?usp=sharing
并获取 ID - 例如。 1TLNdIufzwesDbyr_nVTR7Zrx9oRHLM_N 按下载按钮(在 link 处查找),然后在下面的 id 后换入。
import gdown
url = 'https://drive.google.com/uc?id=0B9P1L--7Wd2vNm9zMTJWOGxobkU'
output = '20150428_collected_images.tgz'
gdown.download(url, output, quiet=False)
一般来说,来自 Google 驱动器的共享文件的 URL 看起来像这样
https://drive.google.com/file/d/1HV6vf8pB-EYnjcJcH65eGZVMa2v2tcMh/view?usp=sharing
其中 1HV6vf8pB-EYnjcJcH65eGZVMa2v2tcMh
对应于文件 ID。
因此,您可以简单地创建一个函数来从 URL 中获取文件 ID,例如 url = https://drive.google.com/file/d/1HV6vf8pB-EYnjcJcH65eGZVMa2v2tcMh/view?usp=sharing
、
def url_to_id(url):
x = url.split("/")
return x[5]
打印 x 会得到
['https:', '', 'drive.google.com', 'file', 'd', '1HV6vf8pB-EYnjcJcH65eGZVMa2v2tcMh', 'view?usp=sharing']
因此,因为我们想要 return 第 6 个数组值,所以我们使用 x[5]
.
这是一个简单的方法,无需 third-party 库和服务帐户。
pip 安装 google-api-core
和 google-api-python-client
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google.oauth2 import service_account
import io
credz = {} #put json credentials her from service account or the like
# More info: https://cloud.google.com/docs/authentication
credentials = service_account.Credentials.from_service_account_info(credz)
drive_service = build('drive', 'v3', credentials=credentials)
file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
request = drive_service.files().get_media(fileId=file_id)
#fh = io.BytesIO() # this can be used to keep in memory
fh = io.FileIO('file.tar.gz', 'wb') # this can be used to write to disk
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download %d%%." % int(status.progress() * 100))
这个例子是基于一个类似于RayB的,但是将文件保存在内存中 并且更简单一些,您可以将其粘贴到 colab 中并且可以使用。
import googleapiclient.discovery
import oauth2client.client
from google.colab import auth
auth.authenticate_user()
def download_gdrive(id):
creds = oauth2client.client.GoogleCredentials.get_application_default()
service = googleapiclient.discovery.build('drive', 'v3', credentials=creds)
return service.files().get_media(fileId=id).execute()
a = download_gdrive("1F-yaQB8fdsfsdafm2l8WFjhEiYSHZrCcr")
我尝试使用 google Colaboratory:https://colab.research.google.com/
假设您的可分享 link 是 https://docs.google.com/spreadsheets/d/12hiI0NK7M0KEfscMfyBaLT9gxcZMleeu/edit?usp=sharing&ouid=102608702203033509854&rtpof=true&sd=true
你只需要 id 12hiI0NK7M0KEfscMfyBaLT9gxcZMleeu
单元格中的命令
!gdown 12hiI0NK7M0KEfscMfyBaLT9gxcZMleeu
运行 单元格,您会看到该文件已下载到 /content/Amazon_Reviews.xlsx
注意:应该知道如何使用 Google colab