确保您已经设置了Google Drive API并安装了google-api-python-client
库。要安装库,请运行以下命令:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
接下来,按照以下步骤编写Python代码以检索Google Drive上的照片:
import os.path
import google.auth
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# 设置API凭证
SERVICE_ACCOUNT_FILE = 'path/to/your/credentials.json'
SCOPES = ['https://www.googleapis.com/auth/drive']
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
api_service_name = 'drive'
api_version = 'v3'
drive_service = build(api_service_name, api_version, credentials=credentials)
def get_photos_from_drive(folder_id):
try:
# 获取文件夹中的文件
query = f"'{folder_id}' in parents and mimeType='image/*'"
results = drive_service.files().list(q=query, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No photos found.')
else:
print('Photos:')
for item in items:
print(f"{item['name']} ({item['id']})")
except HttpError as error:
print(f"An error occurred: {error}")
folder_id = 'target_folder_id'
get_photos_from_drive(folder_id)
请确保将SERVICE_ACCOUNT_FILE
设置为对应的凭据文件。同时, 请将folder_id
设置为您想要检索照片的文件夹ID。
领取专属 10元无门槛券
手把手带您无忧上云