如何用Python入门脚本通过Trustpilot API获取访问令牌及评论数据
从Trustpilot API获取私有评论数据的Python入门脚本
前置准备
- 注册Trustpilot开发者账号并创建应用,获取以下信息:
- API Key
- API Secret
- Business Unit ID(访问私有评论必须)
- 安装依赖库:
pip install requests
完整脚本
import requests def get_trustpilot_access_token(api_key, api_secret): """获取Trustpilot API访问令牌""" token_url = "https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken" payload = { "grant_type": "client_credentials", "client_id": api_key, "client_secret": api_secret, "scope": "read:reviews" } response = requests.post(token_url, data=payload) response.raise_for_status() # 捕获请求错误 return response.json()["access_token"] def get_private_reviews(access_token, business_unit_id, limit=10): """获取指定Business Unit的私有评论数据""" reviews_url = f"https://api.trustpilot.com/v1/private/business-units/{business_unit_id}/reviews" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } params = { "limit": limit, "order": "createdat.desc" # 按创建时间倒序排列 } response = requests.get(reviews_url, headers=headers, params=params) response.raise_for_status() return response.json() if __name__ == "__main__": # 替换为你的实际信息 API_KEY = "YOUR_API_KEY" API_SECRET = "YOUR_API_SECRET" BUSINESS_UNIT_ID = "YOUR_BUSINESS_UNIT_ID" try: # 获取访问令牌 access_token = get_trustpilot_access_token(API_KEY, API_SECRET) print("成功获取访问令牌") # 获取私有评论 reviews_data = get_private_reviews(access_token, BUSINESS_UNIT_ID) print(f"获取到{len(reviews_data['reviews'])}条私有评论:") # 打印评论摘要 for review in reviews_data["reviews"]: print(f"- 评分: {review['stars']}, 标题: {review['title']}, 创建时间: {review['createdAt']}") except requests.exceptions.HTTPError as err: print(f"请求错误: {err}")
使用说明
- 替换脚本中的
YOUR_API_KEY、YOUR_API_SECRET和YOUR_BUSINESS_UNIT_ID为你自己的信息 - 运行脚本,会先获取访问令牌,再拉取指定数量的私有评论并打印关键信息
- 如果需要调整评论数量,修改
get_private_reviews函数的limit参数即可
内容的提问来源于stack exchange,提问作者Sander van den Oord
相关产品推荐
相关产品推荐

