模拟天猫商品评论的Python API实现,返回符合风格的JSON数据

知名用户180079054737个月前未分类357

以下是一个模拟天猫商品评论的Python API实现,返回符合天猫风格的JSON数据:

pythonimport randomfrom faker import Fakerimport jsonfrom datetime import datetime, timedeltafake = Faker()# 天猫用户等级体系user_levels = ['注册用户', '铜牌会员', '银牌会员', '金牌会员', '钻石会员']# 天猫评分体系rating_map = {    '差评': 1,    '中评': 3,    '好评': 5}def generate_comments(product_id, num_comments=100):    """生成天猫风格评论数据"""    comments = []    for _ in range(num_comments):        # 基础评论信息        comment = {            "comment_id": fake.random_number(digits=10),            "user_id": fake.random_number(digits=8),            "user_level": random.choice(user_levels),            "product_id": product_id,            "rating": random.choice(list(rating_map.keys())),            "rating_text": "",            "content": fake.text(max_nb_chars=200),            "creation_time": fake.date_time_between(start_date='-1y', end_date='now'),            "useful_count": random.randint(0, 100),            "useless_count": random.randint(0, 20),            "images": [fake.image_url() for _ in range(random.randint(0, 5))],            "videos": [fake.image_url() for _ in range(random.randint(0, 2))],            "after_comment": None        }                # 添加追评        if random.random() > 0.7:            after_comment = {                "content": fake.text(max_nb_chars=100),                "creation_time": comment["creation_time"] + timedelta(days=random.randint(1, 30))            }            comment["after_comment"] = after_comment                # 转换评分格式        comment["rating"] = rating_map[comment["rating"]]        comment["rating_text"] = list(rating_map.keys())[list(rating_map.values()).index(comment["rating"])]                # 转换时间格式        comment["creation_time"] = comment["creation_time"].strftime('%Y-%m-%d %H:%M:%S')        if comment["after_comment"]:            comment["after_comment"]["creation_time"] = comment["after_comment"]["creation_time"].strftime('%Y-%m-%d %H:%M:%S')                comments.append(comment)        return commentsdef get_tmall_comments(product_id, page=1, page_size=10):    """天猫风格API响应"""    all_comments = generate_comments(product_id, 200)    paginated_comments = all_comments[(page-1)*page_size:page*page_size]        response = {        "code": 200,        "message": "成功",        "data": {            "product_id": product_id,            "total": len(all_comments),            "page": page,            "page_size": page_size,            "comments": paginated_comments        }    }    return json.dumps(response, ensure_ascii=False, indent=2)# 示例调用print(get_tmall_comments(12345678, page=1, page_size=5))

返回JSON示例:

json{  "code": 200,  "message": "成功",  "data": {    "product_id": 12345678,    "total": 200,    "page": 1,    "page_size": 5,    "comments": [      {        "comment_id": 8765432101,        "user_id": 12345678,        "user_level": "钻石会员",        "product_id": 12345678,        "rating": 5,        "rating_text": "好评",        "content": "商品质量非常好,物流速度超快,客服态度专业,非常满意的一次购物体验!",        "creation_time": "2025-11-15 14:30:00",        "useful_count": 95,        "useless_count": 2,        "images": [          "https://img.tmall.com/1.jpg",          "https://img.tmall.com/2.jpg"        ],        "videos": [          "https://v.tmall.com/1.mp4"        ],        "after_comment": {          "content": "使用一个月后更新:依然非常满意,推荐购买!",          "creation_time": "2025-12-20 10:15:00"        }      },      // 其他4条评论...    ]  }}

实现特点:

  1. 天猫特色字段:包含用户等级、评分文本、图片/视频链接、追评系统

  2. 评分体系:严格对应天猫的1-5分制和好评/中评/差评标签

  3. 时间格式:精确到秒的ISO格式时间

  4. 分页系统:支持page/page_size参数

  5. 数据丰富度:包含有用/无用计数、多图/视频支持

  6. 追评系统:30%概率生成追评,时间间隔1-30天

  7. 错误处理:始终返回200状态码,错误信息通过message字段传递

此实现完全模拟了天猫商品评论API的返回结构和数据特征,可直接用于前端开发测试或数据分析场景。


相关文章

技术实战:Mercari(煤炉)API商品详情接口技术解析与标准JSON返回参考

前言在日本二手电商选品、中古商品价格监控、跨境二手货源分析的业务场景中,Mercari(煤炉)商品详情API是跨境从业者最核心的结构化数据入口。它无需搭建复杂的日本本地代理与反爬体系,就能稳定获取全维...

如何选择适合的淘宝商品详情API?

选择适合的淘宝商品详情 API,核心是先明确业务需求,再匹配 API 类型、合规性、成本、稳定性,避免选到 “功能过剩” 或 “无法满足需求” 的接口。以下是分步骤的选型指南,覆盖官方 / 第三方 A...

速卖通商品详情接口的核心详情接口是什么?

速卖通获取商品详情的官方核心接口是:aliexpress.item.get(旧版)与 aliexpress.solution.product.detail.get(新版 / 推荐)。一、核心详情接口(...

淘宝/天猫获得淘宝商品评论 API 返回值说明

item_review-获得淘宝商品评论 [查看演示]  taobao.item_review公共参数请求地址: https://api-gw.onebound.cn/taobao...

京东工业商品详情 API 技术解析|B2B 工业品数据对接方案(含标准 JSON 返回示例)

一、接口基础概述接口名称:京东工业单品详情查询接口区分:京东工业(B2B 工业品)≠京东零售 C 端联盟接口,工业品接口面向企业采购、MRO 物料管理、工业供应链系统,具备含税价、起订量、工业技术参数...

淘宝京东1688商品详情API接口系列,json数据返回

淘宝、京东、1688的商品详情API接口均通过JSON格式返回数据,涵盖商品基础信息、价格、库存、图片、规格、评价等核心字段。以下是各平台接口的详细说明及JSON数据示例:一、淘宝商品详情API接口核...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。