
本文详解如何通过 google drive api 正确获取 google docs 中的评论文本及其所引用的原文(quoted text),解决因误用 docs api 导致 comments 返回空列表的问题,并提供可运行的完整示例代码与关键配置说明。
本文详解如何通过 google drive api 正确获取 google docs 中的评论文本及其所引用的原文(quoted text),解决因误用 docs api 导致 comments 返回空列表的问题,并提供可运行的完整示例代码与关键配置说明。
Google Docs API 的 documents.get() 方法不返回评论数据——这是导致原始代码中 comments 列表为空的根本原因。评论(Comments)在 Google 生态中属于 Drive 文件级元数据,而非文档正文内容,因此必须调用 Google Drive API v3 的 comments.list 端点,而非 Docs API。
✅ 正确流程概览
- 启用 Google Cloud 控制台中的 Drive API v3(非 Docs API);
- 使用服务账号或 OAuth 2.0 凭据授权;
- 调用 service.comments().list(fileId=DOC_ID, fields='*') 获取完整评论对象;
- 从每个评论中提取 content(评论正文)和 quotedFileContent.value(被选中的原文);
- 注意权限:目标文档必须明确共享给服务账号邮箱(如 your-sa@project.iam.gserviceaccount.com),否则返回空列表且无错误提示。
? 完整可运行示例代码
from googleapiclient.discovery import build
from googleapiclient.http import Http
from oauth2client.service_account import ServiceAccountCredentials
# 替换为你的实际配置
SERVICE_ACCOUNT_FILE = 'credentials.json'
DOCUMENT_ID = 'YOUR_GOOGLE_DOC_ID' # 如 '1aBcDeFgHiJkLmNoPqRsTuVwXyZ'
def get_credentials():
scopes = ['https://www.googleapis.com/auth/drive.readonly']
return ServiceAccountCredentials.from_json_keyfile_name(
SERVICE_ACCOUNT_FILE, scopes
)
def read_comments(comments):
"""提取评论内容 + 被批注原文,返回结构化列表"""
result = []
for comment in comments:
# 评论主体文本(用户输入)
content = comment.get('content', '').strip()
# 被选中的原文(仅当用户高亮文本后添加评论时存在)
quoted = comment.get('quotedFileContent', {}).get('value', '').strip()
if content or quoted:
result.append({
'comment': content,
'quoted_text': quoted,
'author': comment.get('author', {}).get('displayName', 'Unknown'),
'created_time': comment.get('createdTime', '')
})
return result
def main():
credentials = get_credentials()
http = credentials.authorize(Http())
# ✅ 关键:使用 Drive API v3,不是 Docs API
drive_service = build('drive', 'v3', http=http)
try:
# 获取所有评论(fields='*' 表示返回全部字段,便于调试)
results = drive_service.comments().list(
fileId=DOCUMENT_ID,
fields='comments(content,quotedFileContent/value,author/displayName,createdTime)'
).execute()
comments = results.get('comments', [])
extracted = read_comments(comments)
print(f"共找到 {len(extracted)} 条有效评论:\n")
for i, item in enumerate(extracted, 1):
print(f"[{i}] 评论人: {item['author']} | 时间: {item['created_time']}")
print(f" ? 原文引用: '{item['quoted_text']}'")
print(f" ? 评论内容: '{item['comment']}'\n")
except Exception as e:
print(f"API 调用失败:{e}")
print("常见原因:1) Drive API 未启用;2) 文档未共享给服务账号;3) 文档 ID 错误")
if __name__ == '__main__':
main()⚠️ 关键注意事项
- API 选择不可混淆:docs.v1 用于读取文档结构/正文;drive.v3 才提供 comments.list;
- 权限即一切:服务账号邮箱必须以“编辑者”或“评论者”身份被添加到目标文档的共享列表中(在 Google Docs 右上角「共享」→「添加人员」);
- quotedFileContent 仅在用户先选中文本再右键添加评论时存在;若直接在空白处插入评论(如页脚、图片旁),该字段为空;
- 若需处理回复(replies)、状态(resolved/pending)或删除标记(deleted: true),可在 fields 参数中显式添加对应字段;
- 生产环境建议使用 fields 限定返回字段(如示例中所示),避免传输冗余数据。
✅ 总结
要可靠提取 Google 文档的评论与上下文原文,请牢记:用 Drive API,配正确权限,查 quotedFileContent.value。抛弃 docs.documents().get().get('comments') 这一无效路径,转向 drive.comments().list(),即可精准捕获协作过程中的所有批注语义信息。









