如何编写代码批量获取Google Drive文件夹中所有图片的评论?
批量获取Google Drive文件夹内图片的评论
嘿,你已经搞定了单张图片评论获取的核心逻辑,现在要批量处理文件夹里的图片对吧?我来帮你扩展代码实现这个需求~
实现思路
- 先写一个函数,用来获取目标文件夹下所有图片的ID和名称
- 循环遍历每个图片ID,调用你已有的
retrieve_comments函数 - 处理无评论的边界情况,避免直接取索引导致报错
完整可运行代码
from googleapiclient.discovery import build from google.oauth2.credentials import Credentials from googleapiclient.errors import HttpError def retrieve_comments(service, file_id): """Retrieve a list of comments for a file. Args: service: Drive API service instance. file_id: ID of the file to retrieve comments for. Returns: List of comments, or empty list if no comments exist. """ try: comments = service.comments().list(fileId=file_id).execute() return comments.get('items', []) except HttpError as error: print(f'An error occurred when fetching comments for file {file_id}: {error}') return [] def get_folder_image_files(service, folder_id): """Retrieve all image files from a specified Google Drive folder. Args: service: Drive API service instance. folder_id: ID of the target folder. Returns: List of file objects containing ID and name. """ # 覆盖常见的图片格式MIME类型,可根据需求增减 image_mime_types = [ 'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp' ] # 构建查询条件:只取目标文件夹下的图片文件 query = f"'{folder_id}' in parents and mimeType in ({','.join([f'{repr(mt)}' for mt in image_mime_types])})" try: results = service.files().list( q=query, fields="files(id, name)" # 只获取需要的ID和名称字段,减少数据传输 ).execute() return results.get('files', []) except HttpError as error: print(f'An error occurred when fetching folder files: {error}') return [] if __name__ == '__main__': # 配置参数 SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.metadata.readonly'] TOKEN_PATH = 'token.json' # 替换成你的目标文件夹ID(可以从文件夹的URL里提取) TARGET_FOLDER_ID = '你的文件夹ID' # 初始化Drive服务 credentials = Credentials.from_authorized_user_file(TOKEN_PATH, SCOPES) service = build('drive', 'v2', credentials=credentials) # 获取文件夹内所有图片 image_files = get_folder_image_files(service, TARGET_FOLDER_ID) if not image_files: print('未在目标文件夹中找到图片文件') exit() # 批量获取并输出评论 print(f'开始处理 {len(image_files)} 张图片...') for file in image_files: file_id = file['id'] file_name = file['name'] comments = retrieve_comments(service, file_id) if comments: # 默认取第一条评论,要是需要所有评论,改成循环遍历comments列表即可 first_comment = comments[0]['content'] print(f"图片「{file_name}」的第一条评论: {first_comment}") else: print(f"图片「{file_name}」暂无评论")
关键注意点
- 一定要把代码里的
TARGET_FOLDER_ID替换成你自己的Google Drive文件夹ID - 如果需要获取某张图片的所有评论,把输出第一条评论的部分改成循环遍历
comments列表就行 - 代码已经处理了无评论文件和API请求错误的情况,不会轻易崩溃
- 当前的权限范围已经足够,不需要额外调整SCOPES
内容的提问来源于stack exchange,提问作者Sasha Casas
相关产品推荐
相关产品推荐

