使用Python调用Google API获取商家评论时的问题及解决咨询
解决Google商家评论API调用问题
问题根源
mybusinessv4服务已被拆分,评论功能独立为My Business Reviews API,原服务不再支持直接调用评论接口mybusinessbusinessinformationAPI仅负责商家基础信息管理,不包含评论查询能力,因此会触发AttributeError
正确解决方案
使用My Business Reviews API(服务名mybusinessreviews,版本v1),注意该API需要OAuth 2.0认证(API Key仅适用于公开数据接口,无法访问商家评论这类私有数据)。
步骤1:前置准备
在Google Cloud控制台启用「My Business Reviews API」,并创建OAuth 2.0客户端ID,通过授权流获取凭证文件(如token.json)。
步骤2:正确代码示例
from googleapiclient.discovery import build from google.oauth2.credentials import Credentials # 加载OAuth2凭证(替换为你的凭证文件路径) credentials = Credentials.from_authorized_user_file('token.json') # 初始化Reviews API服务 service = build('mybusinessreviews', 'v1', credentials=credentials) # 替换为完整的商家位置ID(格式:accounts/{account_id}/locations/{location_id}) parent = 'accounts/123456789/locations/987654321' # 请求评论列表 reviews_response = service.accounts().locations().reviews().list(parent=parent).execute() # 遍历输出评论数据 for review in reviews_response.get('reviews', []): print(f"评论内容: {review.get('comment', '无评论内容')}") print(f"评分: {review.get('starRating')}") print(f"评论者: {review.get('reviewer', {}).get('displayName', '匿名用户')}") print('---')
关键注意事项
- 位置ID必须使用完整格式
accounts/{account_id}/locations/{location_id},不能仅传入locations/{id} - 必须使用OAuth 2.0认证,API Key无权限访问商家私有评论数据
- 确保授权的OAuth账号拥有对应商家的管理权限
内容的提问来源于stack exchange,提问作者André Pletschette
相关产品推荐
相关产品推荐

