蘑菇街 item_get 接口深度分析及 Python 实现

蘑菇街的 item_get 接口是用于获取蘑菇街平台商品详情的核心接口,能够获取商品的完整信息,包括基础属性、价格、库存、规格、促销活动、店铺信息等。该接口对于电商数据分析、竞品监控、多平台商品对比等场景具有重要价值,尤其适用于时尚服饰、美妆护肤等蘑菇街优势品类的分析。

一、接口核心特性分析

  1. 接口功能与定位
  • 核心功能:获取蘑菇街指定商品的全方位详情数据,包括但不限于商品基本信息、价格体系、库存状态、规格参数、促销活动等

  • 数据特点:返回数据与蘑菇街 APP / 网页端展示保持一致,包含平台特有的社交电商元素(如达人推荐、买家秀等)

  • 应用场景

    • 电商比价工具:对比不同平台同款时尚商品价格
    • 竞品分析系统:监控竞争对手的商品策略和促销活动
    • 导购平台:为用户提供商品详细信息和购买指引
    • 数据分析工具:研究时尚电商市场趋势和消费偏好
  1. 认证机制 蘑菇街开放平台采用 appkey + access_token 的认证方式,具体流程如下:
  • 开发者在蘑菇街开放平台注册应用,获取 appkeyappsecret
  • 使用 appkeyappsecret 获取 access_token(有有效期限制,通常为 2 小时)
  • 每次接口调用时,在请求头或参数中携带 access_token 进行身份验证
  1. 核心参数与响应结构

请求参数

参数名 类型 是否必填 说明
item_id String 商品 ID,可从蘑菇街商品详情页 URL 中获取
access_token String 访问令牌
fields String 需要返回的字段,多个字段用逗号分隔,默认返回所有字段

响应核心字段

  • 商品基础信息:商品 ID、名称、主图、详情图、品牌信息、标签等
  • 价格信息:原价、促销价、会员价、优惠券信息等
  • 库存信息:总库存、规格库存、库存状态等
  • 规格参数:颜色、尺寸等规格组合及对应的价格和库存
  • 促销信息:活动类型、优惠方式、活动时间等
  • 店铺信息:店铺 ID、名称、评分、粉丝数等
  • 社交元素:达人推荐语、买家秀、点赞数、收藏数等

二、Python 脚本实现

以下是调用蘑菇街 item_get 接口的完整 Python 实现,包含令牌获取、接口调用、数据解析等功能: import requests import time import json import logging import hashlib from typing import Dict, Optional, List from requests.exceptions import RequestException

配置日志

logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" )

class MogujieItemAPI: def init (self, appkey: str, appsecret: str): """ 初始化蘑菇街API客户端 :param appkey: 蘑菇街开放平台appkey :param appsecret: 蘑菇街开放平台appsecret """ self.appkey = appkey self.appsecret = appsecret self.base_url = "api.mogujie.com" self.access_token = None self.token_expires_at = 0 # token过期时间戳 self.session = requests.Session() # 设置默认请求头 self.session.headers.update({ "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" })

python 复制代码
def _get_access_token(self) -> Optional[str]:
    """获取访问令牌"""
    # 检查token是否有效
    if self.access_token and self.token_expires_at > time.time() + 60:
        return self.access_token
        
    logging.info("获取新的access_token")
    url = f"{self.base_url}/oauth/token"
    
    params = {
        "grant_type": "client_credentials",
        "client_id": self.appkey,
        "client_secret": self.appsecret
    }
    
    try:
        response = self.session.post(url, json=params, timeout=10)
        response.raise_for_status()
        result = response.json()
        
        if "access_token" in result:
            self.access_token = result["access_token"]
            self.token_expires_at = time.time() + result.get("expires_in", 7200)  # 默认为2小时
            return self.access_token
        else:
            logging.error(f"获取access_token失败: {result.get('error_description', '未知错误')}")
            return None
            
    except RequestException as e:
        logging.error(f"获取access_token请求异常: {str(e)}")
        return None

def get_item_details(self, item_id: str, fields: Optional[str] = None) -> Optional[Dict]:
    """
    获取商品详情
    :param item_id: 商品ID
    :param fields: 需要返回的字段,多个用逗号分隔
    :return: 商品详情数据
    """
    # 获取有效的access_token
    if not self._get_access_token():
        return None
        
    url = f"{self.base_url}/item/get"
    
    # 构建请求参数
    params = {
        "item_id": item_id,
        "access_token": self.access_token
    }
    
    # 添加需要返回的字段
    if fields:
        params["fields"] = fields
        
    try:
        response = self.session.get(url, params=params, timeout=15)
        response.raise_for_status()
        result = response.json()
        
        # 检查响应状态
        if result.get("code") == 0:
            # 格式化商品数据
            return self._format_item_data(result.get("data", {}))
        else:
            logging.error(f"获取商品详情失败: {result.get('message', '未知错误')} (错误码: {result.get('code')})")
            return None
            
    except RequestException as e:
        logging.error(f"获取商品详情请求异常: {str(e)}")
        return None
    except json.JSONDecodeError:
        logging.error(f"商品详情响应解析失败: {response.text[:200]}...")
        return None

def _format_item_data(self, item_data: Dict) -> Dict:
    """格式化商品数据"""
    # 基础信息
    basic_info = {
        "item_id": item_data.get("item_id"),
        "title": item_data.get("title"),
        "subtitle": item_data.get("subtitle"),
        "brand": {
            "brand_id": item_data.get("brand_id"),
            "brand_name": item_data.get("brand_name")
        },
        "main_images": item_data.get("main_images", []),
        "detail_images": item_data.get("detail_images", []),
        "detail_url": item_data.get("detail_url"),
        "category": {
            "cat_id": item_data.get("cat_id"),
            "cat_name": item_data.get("cat_name"),
            "parent_cat_id": item_data.get("parent_cat_id"),
            "parent_cat_name": item_data.get("parent_cat_name")
        },
        "tags": item_data.get("tags", []),  # 商品标签,如"新品"、"热卖"等
        "desc": item_data.get("desc")  # 商品描述
    }
    
    # 价格信息
    price_info = {
        "original_price": float(item_data.get("original_price", 0)),
        "current_price": float(item_data.get("current_price", 0)),
        "discount": float(item_data.get("discount", 0)),
        "member_price": float(item_data.get("member_price", 0)) if item_data.get("has_member_price") else None,
        "has_member_price": item_data.get("has_member_price", False),
        "coupon_info": item_data.get("coupon_info", {})  # 优惠券信息
    }
    
    # 库存信息
    stock_info = {
        "total_stock": int(item_data.get("total_stock", 0)),
        "sold_count": int(item_data.get("sold_count", 0)),  # 已售数量
        "is_in_stock": item_data.get("is_in_stock", False),
        "limit_buy": item_data.get("limit_buy", 0)  # 限购数量
    }
    
    # 规格信息
    sku_info = {
        "has_sku": item_data.get("has_sku", False),
        "sku_list": [],
        "specs": item_data.get("specs", {})  # 规格定义,如颜色、尺寸等
    }
    
    # 处理规格数据
    if sku_info["has_sku"] and "skus" in item_data:
        for sku in item_data["skus"]:
            sku_info["sku_list"].append({
                "sku_id": sku.get("sku_id"),
                "spec_text": sku.get("spec_text"),  # 规格组合文本,如"红色,XL"
                "spec_values": sku.get("spec_values", []),  # 规格值组合
                "price": float(sku.get("price", 0)),
                "original_price": float(sku.get("original_price", 0)),
                "stock": int(sku.get("stock", 0)),
                "image": sku.get("image")
            })
    
    # 促销信息
    promotion_info = {
        "promotions": item_data.get("promotions", []),  # 促销活动列表
        "start_time": item_data.get("promotion_start_time"),
        "end_time": item_data.get("promotion_end_time"),
        "is_promotion": item_data.get("is_promotion", False)
    }
    
    # 店铺信息
    shop_info = {
        "shop_id": item_data.get("shop_id"),
        "shop_name": item_data.get("shop_name"),
        "shop_logo": item_data.get("shop_logo"),
        "shop_type": item_data.get("shop_type"),  # 店铺类型,如"旗舰店"、"专营店"
        "score": {
            "overall": float(item_data.get("shop_score", {}).get("overall", 0)),
            "description": float(item_data.get("shop_score", {}).get("description", 0)),
            "service": float(item_data.get("shop_score", {}).get("service", 0)),
            "shipping": float(item_data.get("shop_score", {}).get("shipping", 0))
        },
        "fans_count": int(item_data.get("fans_count", 0)),  # 店铺粉丝数
        "good_rate": float(item_data.get("good_rate", 0))  # 好评率
    }
    
    # 社交元素信息(蘑菇街特色)
    social_info = {
        "fav_count": int(item_data.get("fav_count", 0)),  # 收藏数
        "like_count": int(item_data.get("like_count", 0)),  # 点赞数
        "comment_count": int(item_data.get("comment_count", 0)),  # 评论数
        "buyer_show": item_data.get("buyer_show", []),  # 买家秀
        "recommender": item_data.get("recommender", {})  # 推荐达人信息
    }
    
    # 物流信息
    logistics_info = {
        "freight": float(item_data.get("freight", 0)),
        "freight_free": item_data.get("freight_free", False),  # 是否包邮
        "freight_free_amount": float(item_data.get("freight_free_amount", 0)),  # 包邮门槛
        "delivery_time": item_data.get("delivery_time"),  # 发货时间
        "shipping_address": item_data.get("shipping_address")  # 发货地
    }
    
    return {
        "basic_info": basic_info,
        "price_info": price_info,
        "stock_info": stock_info,
        "sku_info": sku_info,
        "promotion_info": promotion_info,
        "shop_info": shop_info,
        "social_info": social_info,
        "logistics_info": logistics_info,
        "raw_data": item_data  # 保留原始数据
    }

示例调用

if name == "main": # 替换为实际的appkey和appsecret(从蘑菇街开放平台获取) APPKEY = "your_appkey" APPSECRET = "your_appsecret" # 替换为目标商品ID ITEM_ID = "12345678"

python 复制代码
# 初始化API客户端
api = MogujieItemAPI(APPKEY, APPSECRET)

# 获取商品详情(可以指定需要返回的字段,如:"item_id,title,current_price,stock")
item_details = api.get_item_details(ITEM_ID)

if item_details:
    print(f"=== 商品详情 ===")
    print(f"商品ID: {item_details['basic_info']['item_id']}")
    print(f"商品标题: {item_details['basic_info']['title']}")
    print(f"品牌: {item_details['basic_info']['brand']['brand_name']}")
    print(f"原价: {item_details['price_info']['original_price']}元")
    print(f"现价: {item_details['price_info']['current_price']}元")
    
    if item_details['price_info']['discount'] > 0:
        print(f"折扣: {item_details['price_info']['discount']}折")
        
    if item_details['price_info']['has_member_price']:
        print(f"会员价: {item_details['price_info']['member_price']}元")
        
    print(f"库存: {item_details['stock_info']['total_stock']}")
    print(f"已售: {item_details['stock_info']['sold_count']}件")
    print(f"店铺: {item_details['shop_info']['shop_name']}")
    print(f"店铺评分: {item_details['shop_info']['score']['overall']}分")
    print(f"收藏数: {item_details['social_info']['fav_count']}")
    print(f"评论数: {item_details['social_info']['comment_count']}")
    
    if item_details['promotion_info']['is_promotion']:
        print(f"\n促销活动:")
        for promo in item_details['promotion_info']['promotions'][:2]:
            print(f"- {promo.get('name')}")
    
    if item_details['sku_info']['has_sku']:
        print(f"\n规格数量: {len(item_details['sku_info']['sku_list'])}")
        for i, sku in enumerate(item_details['sku_info']['sku_list'][:3], 1):
            print(f"  规格{i}: {sku['spec_text']} - {sku['price']}元 - 库存{sku['stock']}")

三、接口调用注意事项

  1. 调用限制与规范
  • QPS 限制:蘑菇街开放平台对 API 调用有严格的 QPS 限制,通常为 10 次 / 秒
  • 数据缓存:建议对商品详情数据进行缓存(缓存时间建议 30-60 分钟),减少重复调用
  • 字段筛选 :不需要全部字段时,通过fields参数指定所需字段,提高接口响应速度
  • 合规使用:获取的商品数据需遵守蘑菇街开放平台的使用规范,不得用于非法用途
  • 社交数据使用:蘑菇街的买家秀、达人推荐等社交元素有额外使用限制,需单独申请权限
  1. 常见错误及解决方案 | 错误码 | 说明 | 解决方案 | | --- | ------------- | ------------------------- | | 400 | 请求参数错误 | 检查请求参数是否完整、格式是否正确 | | 401 | 未授权或 token 无效 | 重新获取 access_token | | 403 | 权限不足 | 检查应用是否已申请相关接口权限,特别是社交数据权限 | | 404 | 商品不存在 | 确认 item_id 是否正确有效 | | 429 | 调用频率超限 | 降低调用频率,实现请求限流 | | 500 | 服务器内部错误 | 稍后重试,或联系蘑菇街技术支持 |

  2. 数据解析要点

  • 价格相关字段可能为字符串类型,需要转换为数值类型
  • 图片 URL 可能需要特殊处理才能直接访问
  • 规格数据结构可能较为复杂,尤其是服饰类商品的颜色和尺寸组合
  • 社交元素数据(如买家秀)可能有分页,需要额外处理
  • 部分字段可能为 null 或不存在,需要做容错处理 四、应用场景与扩展建议 典型应用场景
  • 时尚电商比价平台:对比不同平台时尚商品价格
  • 竞品分析系统:监控竞争对手的商品策略和促销活动
  • 导购平台:为用户提供详细的商品信息和社交评价
  • 时尚趋势分析工具:分析蘑菇街平台上的流行元素和消费趋势 扩展建议
  • 实现批量获取商品详情功能,支持多线程并发请求
  • 添加商品价格变化监控,及时获取价格调整信息
  • 结合搜索接口,实现按关键词获取商品列表并查看详情
  • 开发数据导出功能,支持 CSV、Excel 等格式
  • 对社交元素进行情感分析,提取用户对商品的评价关键词
  • 结合图片识别技术,实现同款商品跨平台搜索和比价 通过合理使用蘑菇街 item_get 接口,开发者可以高效获取蘑菇街商品的详细数据,特别是其丰富的社交电商元素,为时尚电商分析和导购平台构建提供有力支持。使用时需遵守蘑菇街开放平台的相关规定,确保数据使用的合法性和合规性
相关推荐
兵临天下api19 小时前
唯品会 item_search_img 接口深度分析及 Python 实现
trae
兵临天下api19 小时前
唯品会item_get - 获得vip商品详情深度分析及 Python 实现
trae
zooooooooy19 小时前
后端工程师的AI全栈之路
spring boot·trae
用户4099322502121 天前
Pydantic模型验证测试:你的API数据真的安全吗?
后端·ai编程·trae
前端卧龙人2 天前
Trae教你实现ui设计师的3d柱状图
trae
前端卧龙人2 天前
Trae教你实现Canvas 表格,提高渲染性能
trae
前端的日常2 天前
Trae再次发力,帮我们实现输入密码挡住动漫人物眼睛的效果
trae
TimelessHaze2 天前
前端面试必问:深浅拷贝从基础到手写,一篇讲透
前端·trae