京东商品详情深度解析:从接口调用到商业价值挖掘的技术实现

一、技术定位与商业价值重构

京东商品详情接口(jd.union.open.goods.detail.query)作为获取商品核心数据的关键入口,其价值远不止于基础信息展示。与常规实现不同,本文方案聚焦电商全链路数据的深度挖掘,通过价格波动分析、促销策略解码、用户画像关联三大维度,解决零售商关注的 "定价策略优化"" 促销效果预测 ""用户需求匹配" 等核心问题,构建从数据采集到商业决策的完整技术链路。

区别于网络上常见的基础调用示例,本方案实现三大突破:

  • 构建商品动态价格监测系统(支持历史价格追踪与趋势预测)
  • 解码京东复杂促销规则(满减、优惠券、多件折扣的叠加计算)
  • 实现商品与用户画像的智能匹配(基于商品属性与用户标签的关联分析)

二、接口权限与技术门槛解析

1. 特殊权限说明

  • 个人开发者可申请基础权限(需完成实名认证)
  • 联盟权限:获取推广佣金相关数据需加入京东联盟(需企业资质)
  • 高级权限:获取用户评价情感分析、竞品比价数据需单独申请
  • 调用限制:普通账号 QPS=10,企业认证账号 QPS=50,需合理设计请求频率

2. 核心参数与商业数据维度

参数名 类型 说明 商业场景价值
skuIds String 商品 ID 列表(最多 10 个) 批量获取商品数据
fields String 字段列表 精准控制返回数据(减少冗余)
platform Number 平台类型 区分 PC/APP 端价格差异
area String 地区编码 获取区域化价格与库存

点击获取key和secret

三、差异化技术实现:从数据采集到智能分析

1. 商品详情智能采集引擎

突破常规接口限制,实现商品全维度数据采集,包含动态价格追踪:

python

运行

复制代码
import time
import hashlib
import json
import logging
import requests
from typing import Dict, List, Optional, Generator
from datetime import datetime, timedelta
from decimal import Decimal
import pandas as pd
from tqdm import tqdm
import numpy as np

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class JDProductDetailAPI:
    def __init__(self, app_key: str, app_secret: str, access_token: str):
        self.app_key = app_key
        self.app_secret = app_secret
        self.access_token = access_token
        self.api_url = "https://api.jd.com/routerjson"
        self.session = self._init_session()
        # 核心字段配置(商业分析必备)
        self.core_fields = (
            "skuId,spuId,name,brand,category,price,marketPrice,promotion,"
            "stock,image,shopInfo,attribute,comment,limitBuyInfo,seckillInfo,"
            "priceHistory,colorSize,materialService"
        )
        # 地区编码映射(用于区域价格分析)
        self.area_codes = {
            "北京": "1_72_2799_0",
            "上海": "1_28_3241_0",
            "广州": "1_20_2237_0",
            "深圳": "1_20_2238_0"
        }
    
    def _init_session(self) -> requests.Session:
        """初始化会话,配置连接池与超时"""
        session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(
            pool_connections=10,
            pool_maxsize=30,
            max_retries=3
        )
        session.mount('https://', adapter)
        return session
    
    def _generate_sign(self, params: Dict) -> str:
        """生成京东签名(MD5算法)"""
        sorted_params = sorted(params.items(), key=lambda x: x[0])
        sign_str = self.app_secret
        for k, v in sorted_params:
            if v is not None and v != "":
                sign_str += f"{k}{v}"
        sign_str += self.app_secret
        return hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper()
    
    def get_product_details(self, sku_ids: List[str],** kwargs) -> List[Dict]:
        """
        批量获取商品详情,支持多地区价格对比
        :param sku_ids: 商品ID列表(最多10个)
        :param **kwargs: 可选参数
                        - area: 地区名称(如"北京")
                        - platform: 平台类型(1:PC, 2:APP)
                        - need_history: 是否需要价格历史
                        - fields: 自定义字段列表
        :return: 商品详情列表
        """
        if not sku_ids:
            return []
            
        # 每次最多处理10个SKU
        batch_size = 10
        results = []
        
        for i in range(0, len(sku_ids), batch_size):
            batch_skus = sku_ids[i:i+batch_size]
            logger.info(f"处理商品批次: {batch_skus}")
            
            try:
                # 构建请求参数
                params = {
                    "method": "jd.union.open.goods.detail.query",
                    "app_key": self.app_key,
                    "access_token": self.access_token,
                    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "format": "json",
                    "v": "1.0",
                    "sign_method": "md5",
                    "360buy_param_json": json.dumps({
                        "skuIds": batch_skus,
                        "fields": kwargs.get("fields", self.core_fields),
                        "platform": kwargs.get("platform", 2),  # 默认APP端
                        "area": self.area_codes.get(kwargs.get("area", "北京"), "1_72_2799_0")
                    })
                }
                
                # 生成签名
                params["sign"] = self._generate_sign(params)
                
                # 发送请求
                response = self.session.get(
                    self.api_url,
                    params=params,
                    timeout=(10, 30)
                )
                response.raise_for_status()
                result = response.json()
                
                # 处理API错误
                if "error_response" in result:
                    error = result["error_response"]
                    logger.error(f"API错误: {error.get('msg')} (代码: {error.get('code')})")
                    if error.get('code') in [10001, 10002, 10003]:  # 权限错误
                        return results
                    continue
                
                # 解析结果
                data = result.get("jd_union_open_goods_detail_query_response", {})
                goods_list = data.get("result", {}).get("goodsDetails", [])
                
                # 处理商品数据
                for goods in goods_list:
                    parsed_goods = self._parse_product_detail(goods)
                    # 如果需要价格历史,单独获取
                    if kwargs.get("need_history", False):
                        parsed_goods["price_history"] = self._get_price_history(parsed_goods["sku_id"])
                    results.append(parsed_goods)
                
                # 控制请求频率
                time.sleep(1 if len(sku_ids) <= batch_size else 2)
                
            except requests.exceptions.RequestException as e:
                logger.error(f"请求异常: {str(e)},将跳过当前批次")
                time.sleep(5)
            except Exception as e:
                logger.error(f"处理异常: {str(e)},将跳过当前批次")
                time.sleep(3)
        
        return results

2. 商品数据深度解析模块

针对商业分析需求,解析商品价格策略、促销规则和用户反馈:

python

运行

复制代码
    def _parse_product_detail(self, raw_data: Dict) -> Dict:
        """解析商品详情,提取商业关键信息"""
        # 解析价格信息
        price_info = self._parse_price(raw_data.get("price", {}))
        
        # 解析促销信息
        promotions = self._parse_promotions(raw_data.get("promotion", {}))
        
        # 解析库存信息
        stock_info = self._parse_stock(raw_data.get("stock", {}))
        
        # 解析评价信息
        comment_info = self._parse_comments(raw_data.get("comment", {}))
        
        # 解析店铺信息
        shop_info = raw_data.get("shopInfo", {})
        
        # 解析规格信息
        specs = self._parse_specs(raw_data.get("colorSize", {}))
        
        # 解析属性信息
        attributes = self._parse_attributes(raw_data.get("attribute", {}))
        
        return {
            "sku_id": raw_data.get("skuId", ""),
            "spu_id": raw_data.get("spuId", ""),
            "name": raw_data.get("name", ""),
            "brand": raw_data.get("brand", {}).get("name", ""),
            "brand_id": raw_data.get("brand", {}).get("id", ""),
            "category": self._parse_category(raw_data.get("category", [])),
            "price": price_info,
            "promotions": promotions,
            "stock": stock_info,
            "main_image": raw_data.get("image", {}).get("mainImgUrl", ""),
            "images": raw_data.get("image", {}).get("imgList", []),
            "shop": {
                "shop_id": shop_info.get("shopId", ""),
                "shop_name": shop_info.get("shopName", ""),
                "shop_level": shop_info.get("shopLevel", 0),
                "is_self_operated": shop_info.get("isSelfOperated", False)  # 是否自营
            },
            "specs": specs,
            "attributes": attributes,
            "comment": comment_info,
            "limit_buy": raw_data.get("limitBuyInfo", {}),  # 限购信息
            "seckill": raw_data.get("seckillInfo", {})  # 秒杀信息
        }
    
    def _parse_price(self, price_data: Dict) -> Dict:
        """解析价格信息,计算实际支付价格"""
        current_price = Decimal(str(price_data.get("currentPrice", 0)))
        market_price = Decimal(str(price_data.get("marketPrice", 0)))
        
        # 计算折扣率
        discount_rate = 0
        if market_price > 0:
            discount_rate = round(float(current_price / market_price), 4)
        
        return {
            "current": current_price,
            "market": market_price,
            "discount_rate": discount_rate,
            "price_trend": price_data.get("priceTrend", []),  # 近期价格趋势
            "original": Decimal(str(price_data.get("originalPrice", 0)))  # 原价
        }
    
    def _parse_promotions(self, promotion_data: Dict) -> Dict:
        """解析促销信息,计算最优购买方案"""
        # 提取各类促销
        cash_coupons = promotion_data.get("cashCoupon", [])  # 京券
        discount_coupons = promotion_data.get("discountCoupon", [])  # 折扣券
       满减 = promotion_data.get("满减", [])  # 满减活动
        multi_discount = promotion_data.get("multiDiscount", [])  # 多件折扣
        
        # 计算最优优惠券
        best_coupon = self._find_best_coupon(cash_coupons + discount_coupons)
        
        # 计算最优满减
        best_full_reduction = self._find_best_full_reduction(满减)
        
        # 计算最优多件折扣
        best_multi = self._find_best_multi_discount(multi_discount)
        
        return {
            "cash_coupons": cash_coupons,
            "discount_coupons": discount_coupons,
            "full_reduction": 满减,
            "multi_discount": multi_discount,
            "best_coupon": best_coupon,
            "best_full_reduction": best_full_reduction,
            "best_multi": best_multi,
            "can_combine": self._check_promotion_combinability(best_coupon, best_full_reduction, best_multi)
        }
    
    def _find_best_coupon(self, coupons: List[Dict]) -> Optional[Dict]:
        """找出最优惠的优惠券"""
        if not coupons:
            return None
            
        # 计算每张优惠券的优惠力度
        for coupon in coupons:
            if coupon.get("type") == "CASH":  # 京券,直接减钱
                coupon["value"] = Decimal(str(coupon.get("discount", 0)))
            else:  # 折扣券
                coupon["value"] = 1 - Decimal(str(coupon.get("discount", 1)))  # 折扣力度
            
        # 按优惠力度排序,取最大的
        return max(coupons, key=lambda x: x["value"])
    
    def _find_best_full_reduction(self, full_reductions: List[Dict]) -> Optional[Dict]:
        """找出最优满减方案"""
        if not full_reductions:
            return None
            
        # 计算满减力度(减免金额/满减门槛)
        for fr in full_reductions:
            threshold = Decimal(str(fr.get("full", 0)))
            reduction = Decimal(str(fr.get("reduction", 0)))
            fr["ratio"] = float(reduction / threshold) if threshold > 0 else 0
            
        # 按力度排序,取最大的
        return max(full_reductions, key=lambda x: x["ratio"])
    
    def _find_best_multi_discount(self, multi_discounts: List[Dict]) -> Optional[Dict]:
        """找出最优多件折扣方案"""
        if not multi_discounts:
            return None
            
        # 计算折扣力度
        for md in multi_discounts:
            md["discount_rate"] = Decimal(str(md.get("discount", 1)))
            
        # 按折扣力度排序,取最小的(折扣最大)
        return min(multi_discounts, key=lambda x: x["discount_rate"])
    
    def _check_promotion_combinability(self, coupon: Dict, full_red: Dict, multi: Dict) -> Dict:
        """检查促销是否可以叠加使用"""
        # 实际场景中需要根据京东规则判断,这里简化处理
        return {
            "coupon_with_full_red": bool(coupon and full_red),
            "coupon_with_multi": bool(coupon and multi),
            "full_red_with_multi": bool(full_red and multi),
            "all_three": bool(coupon and full_red and multi)
        }
    
    def _parse_stock(self, stock_data: Dict) -> Dict:
        """解析库存信息,评估供货能力"""
        stock_num = int(stock_data.get("stockNum", 0))
        
        # 库存紧张程度
        stock_level = "充足"
        if stock_num <= 0:
            stock_level = "无货"
        elif stock_num <= 10:
            stock_level = "紧张"
        elif stock_num <= 50:
            stock_level = "一般"
        
        return {
            "quantity": stock_num,
            "level": stock_level,
            "limit": int(stock_data.get("limitNum", 0)),  # 限购数量
            "fresh_stock": stock_data.get("freshStock", False)  # 是否现货
        }
    
    def _parse_comments(self, comment_data: Dict) -> Dict:
        """解析评价信息,提取用户反馈要点"""
        # 情感分析(简化版)
        positive_ratio = 0
        total = int(comment_data.get("commentCount", 0))
        good = int(comment_data.get("goodCount", 0))
        
        if total > 0:
            positive_ratio = round(good / total * 100, 1)
        
        # 提取评价标签
        tags = []
        for tag in comment_data.get("commentTagStatistics", []):
            tags.append({
                "name": tag.get("name", ""),
                "count": tag.get("count", 0),
                "ratio": round(tag.get("count", 0) / total * 100, 1) if total > 0 else 0
            })
        
        # 按提及次数排序
        tags.sort(key=lambda x: x["count"], reverse=True)
        
        return {
            "total": total,
            "good": good,
            "positive_ratio": positive_ratio,
            "average_score": float(comment_data.get("averageScore", 0)),
            "tags": tags[:10],  # 取前10个热门标签
            "has_image": comment_data.get("hasImageComment", False)
        }
    
    def _parse_category(self, category_data: List) -> Dict:
        """解析分类信息,构建分类路径"""
        categories = {
            "level1": "", "level1_id": "",
            "level2": "", "level2_id": "",
            "level3": "", "level3_id": ""
        }
        
        for i, cat in enumerate(category_data[:3]):  # 最多三级分类
            level = f"level{i+1}"
            categories[level] = cat.get("name", "")
            categories[f"{level}_id"] = cat.get("id", "")
            
        return categories
    
    def _parse_specs(self, spec_data: Dict) -> List[Dict]:
        """解析规格信息,提取SKU对应关系"""
        specs = []
        for spec in spec_data.get("sku2Attr", []):
            spec_info = {
                "sku_id": spec.get("skuId", ""),
                "price": Decimal(str(spec.get("price", 0))),
                "stock": int(spec.get("stock", 0)),
                "attributes": []
            }
            
            # 解析规格属性(如颜色、尺寸等)
            for attr in spec.get("attr", []):
                spec_info["attributes"].append({
                    "name": attr.get("name", ""),
                    "value": attr.get("value", "")
                })
            
            specs.append(spec_info)
        
        return specs
    
    def _parse_attributes(self, attribute_data: Dict) -> Dict:
        """解析商品属性,构建属性字典"""
        attributes = {
            "basic": {},  # 基本属性
            "detail": {},  # 详细属性
            "after_sale": {}  # 售后服务
        }
        
        for attr in attribute_data.get("baseAttrs", []):
            attributes["basic"][attr.get("name", "")] = attr.get("value", "")
            
        for attr in attribute_data.get("otherAttrs", []):
            attributes["detail"][attr.get("name", "")] = attr.get("value", "")
            
        for attr in attribute_data.get("materialService", []):
            attributes["after_sale"][attr.get("name", "")] = attr.get("value", "")
            
        return attributes

3. 商业智能分析引擎

基于商品数据,实现价格预测、用户偏好分析和竞品对比:

python

运行

复制代码
    def _get_price_history(self, sku_id: str, days: int = 30) -> List[Dict]:
        """获取商品价格历史(模拟实现,实际需调用专门接口)"""
        # 实际应用中应调用价格历史接口,这里模拟数据
        history = []
        end_date = datetime.now()
        
        for i in range(days, 0, -1):
            date = (end_date - timedelta(days=i)).strftime("%Y-%m-%d")
            # 生成模拟价格波动(基于当前价格上下浮动10%)
            base_price = float(self.get_product_details([sku_id])[0]["price"]["current"])
            fluctuate = np.random.uniform(-0.1, 0.1)  # 随机波动-10%到10%
            price = round(base_price * (1 + fluctuate), 2)
            
            history.append({
                "date": date,
                "price": price,
                "promotion": np.random.choice([True, False], p=[0.3, 0.7])  # 30%概率有促销
            })
            
        return history
    
    def predict_price_trend(self, sku_id: str, days: int = 7) -> List[Dict]:
        """预测未来价格趋势"""
        # 获取历史价格
        history = self._get_price_history(sku_id, 30)
        
        # 简单线性回归预测
        from sklearn.linear_model import LinearRegression
        
        # 准备数据
        X = np.array([i for i in range(len(history))]).reshape(-1, 1)
        y = np.array([h["price"] for h in history])
        
        # 训练模型
        model = LinearRegression()
        model.fit(X, y)
        
        # 预测未来价格
        future_dates = [(datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d") for i in range(1, days+1)]
        future_X = np.array([len(history) + i for i in range(days)]).reshape(-1, 1)
        predictions = model.predict(future_X)
        
        # 加入波动
        predictions = [round(p * (1 + np.random.uniform(-0.05, 0.05)), 2) for p in predictions]
        
        return [{"date": d, "predicted_price": p} for d, p in zip(future_dates, predictions)]
    
    def analyze_best_buying_strategy(self, sku_id: str, quantity: int = 1) -> Dict:
        """分析最优购买策略"""
        # 获取商品详情
        product = self.get_product_details([sku_id])[0]
        price = product["price"]["current"]
        promotions = product["promotions"]
        
        # 计算各种方案的实际支付金额
        strategies = []
        
        # 1. 无促销
        strategies.append({
            "strategy": "无促销",
            "total_price": price * quantity,
            "per_unit": price,
            "savings": 0
        })
        
        # 2. 仅用优惠券
        if promotions["best_coupon"]:
            coupon = promotions["best_coupon"]
            coupon_value = Decimal(str(coupon.get("discount", 0)))
            total = max(price * quantity - coupon_value, 0)
            strategies.append({
                "strategy": f"使用优惠券: {coupon.get('name')}",
                "total_price": total,
                "per_unit": total / quantity,
                "savings": price * quantity - total
            })
        
        # 3. 仅用满减
        if promotions["best_full_reduction"]:
            fr = promotions["best_full_reduction"]
            threshold = Decimal(str(fr.get("full", 0)))
            reduction = Decimal(str(fr.get("reduction", 0)))
            
            # 计算需要购买的数量以满足满减
            need_qty = max(quantity, int((threshold / price).quantize(Decimal('1'), rounding=ROUND_UP)))
            total = price * need_qty - reduction
            
            strategies.append({
                "strategy": f"满减: 满{threshold}减{reduction}",
                "total_price": total,
                "need_quantity": need_qty,
                "per_unit": total / need_qty,
                "savings": price * need_qty - total
            })
        
        # 4. 仅用多件折扣
        if promotions["best_multi"]:
            multi = promotions["best_multi"]
            buy_count = multi.get("buyCount", 1)
            discount = Decimal(str(multi.get("discount", 1)))
            
            # 计算最佳购买数量
            need_qty = max(quantity, ((quantity + buy_count - 1) // buy_count) * buy_count)
            total = price * need_qty * discount
            
            strategies.append({
                "strategy": f"多件折扣: {buy_count}件{discount*10}折",
                "total_price": total,
                "need_quantity": need_qty,
                "per_unit": total / need_qty,
                "savings": price * need_qty - total
            })
        
        # 5. 组合促销(如果允许)
        if promotions["can_combine"]["coupon_with_full_red"] and promotions["best_coupon"] and promotions["best_full_reduction"]:
            coupon = promotions["best_coupon"]
            fr = promotions["best_full_reduction"]
            
            coupon_value = Decimal(str(coupon.get("discount", 0)))
            threshold = Decimal(str(fr.get("full", 0)))
            reduction = Decimal(str(fr.get("reduction", 0)))
            
            need_qty = max(quantity, int((threshold / price).quantize(Decimal('1'), rounding=ROUND_UP)))
            total = max(price * need_qty - reduction - coupon_value, 0)
            
            strategies.append({
                "strategy": f"优惠券+满减",
                "total_price": total,
                "need_quantity": need_qty,
                "per_unit": total / need_qty,
                "savings": price * need_qty - total
            })
        
        # 找出最优策略
        best_strategy = min(strategies, key=lambda x: x["per_unit"])
        
        return {
            "base_price": price,
            "quantity": quantity,
            "strategies": strategies,
            "best_strategy": best_strategy,
            "estimated_savings": best_strategy["savings"]
        }
    
    def match_user_preferences(self, product: Dict, user_profile: Dict) -> Dict:
        """匹配商品与用户偏好"""
        # 简单匹配算法
        score = 0
        reasons = []
        
        # 品牌匹配
        if user_profile.get("preferred_brands", []):
            if product["brand"] in user_profile["preferred_brands"]:
                score += 20
                reasons.append(f"匹配用户偏好品牌: {product['brand']}")
        
        # 价格区间匹配
        price_range = user_profile.get("price_range", [0, 10000])
        if price_range[0] <= float(product["price"]["current"]) <= price_range[1]:
            score += 15
            reasons.append(f"价格在用户偏好区间内: {price_range[0]}-{price_range[1]}元")
        
        # 评价匹配
        if product["comment"]["positive_ratio"] >= user_profile.get("min_positive_ratio", 90):
            score += 10
            reasons.append(f"好评率达标: {product['comment']['positive_ratio']}%")
        
        # 促销匹配
        if user_profile.get("like_promotion", False) and len(product["promotions"]["cash_coupons"]) > 0:
            score += 15
            reasons.append("包含用户喜欢的促销活动")
        
        # 分类匹配
        if user_profile.get("interested_categories", []):
            category_path = f"{product['category']['level1']}-{product['category']['level2']}"
            if any(c in category_path for c in user_profile["interested_categories"]):
                score += 20
                reasons.append(f"匹配用户感兴趣分类: {category_path}")
        
        # 服务匹配
        if user_profile.get("need_after_sale", False):
            after_sale = product["attributes"]["after_sale"]
            if "七天无理由" in after_sale.values() and "上门取件" in after_sale.values():
                score += 20
                reasons.append("提供用户需要的售后服务")
        
        return {
            "match_score": min(score, 100),  # 满分100
            "match_reasons": reasons,
            "suggestions": self._generate_purchase_suggestions(score, product)
        }
    
    def _generate_purchase_suggestions(self, score: int, product: Dict) -> List[str]:
        """生成购买建议"""
        suggestions = []
        
        if score >= 80:
            suggestions.append("该商品非常符合您的偏好,推荐购买")
        elif score >= 60:
            suggestions.append("该商品比较符合您的偏好,可以考虑购买")
        elif score >= 40:
            suggestions.append("该商品部分符合您的偏好,建议对比后再决定")
        else:
            suggestions.append("该商品不太符合您的偏好,建议查看其他类似商品")
        
        # 价格相关建议
        if product["price"]["price_trend"] and len(product["price"]["price_trend"]) >= 7:
            recent_prices = [float(p["price"]) for p in product["price"]["price_trend"][-7:]]
            current_price = float(product["price"]["current"])
            
            if current_price < min(recent_prices):
                suggestions.append("当前价格为近7天最低,适合入手")
            elif current_price > max(recent_prices):
                suggestions.append("当前价格为近7天最高,建议观望")
        
        # 库存相关建议
        if product["stock"]["level"] == "紧张":
            suggestions.append(f"库存紧张(剩余{product['stock']['quantity']}件),如需购买请尽快")
        elif product["stock"]["level"] == "无货":
            suggestions.append("当前无货,建议设置到货提醒")
        
        return suggestions

四、完整应用示例与结果解析

python

运行

复制代码
    def export_product_analysis(self, product: Dict, analysis: Dict, export_path: str) -> bool:
        """导出商品分析报告为Excel"""
        try:
            with pd.ExcelWriter(export_path) as writer:
                # 1. 基本信息
                basic_info = {
                    "商品ID": product["sku_id"],
                    "商品名称": product["name"],
                    "品牌": product["brand"],
                    "分类": f"{product['category']['level1']} > {product['category']['level2']} > {product['category']['level3']}",
                    "当前价格": float(product["price"]["current"]),
                    "市场价": float(product["marketPrice"]),
                    "折扣率": product["price"]["discount_rate"],
                    "店铺名称": product["shop"]["shop_name"],
                    "是否自营": product["shop"]["is_self_operated"]
                }
                pd.DataFrame([basic_info]).to_excel(writer, sheet_name="基本信息", index=False)
                
                # 2. 价格历史与预测
                if "price_history" in product:
                    price_history_df = pd.DataFrame(product["price_history"])
                    price_history_df.to_excel(writer, sheet_name="价格历史", index=False)
                
                # 3. 促销信息
                promotions_df = pd.DataFrame([{
                    "最佳优惠券": analysis["best_strategy"]["strategy"] if "best_strategy" in analysis else "",
                    "最优满减": promotions["best_full_reduction"]["full"] + "减" + promotions["best_full_reduction"]["reduction"] if promotions["best_full_reduction"] else "",
                    "最优多件折扣": f"{promotions['best_multi']['buyCount']}件{promotions['best_multi']['discount']*10}折" if promotions["best_multi"] else "",
                    "可叠加促销": str(analysis["best_strategy"]["strategy"]) if "best_strategy" in analysis else ""
                }])
                promotions_df.to_excel(writer, sheet_name="促销信息", index=False)
                
                # 4. 评价分析
                comments_df = pd.DataFrame([{
                    "总评价数": product["comment"]["total"],
                    "好评数": product["comment"]["good"],
                    "好评率": product["comment"]["positive_ratio"],
                    "平均评分": product["comment"]["average_score"]
                }])
                comments_df.to_excel(writer, sheet_name="评价分析", index=False)
                
                # 5. 购买策略
                if "strategies" in analysis:
                    strategies_df = pd.DataFrame(analysis["strategies"])
                    strategies_df.to_excel(writer, sheet_name="购买策略", index=False)
            
            logger.info(f"商品分析报告已导出至: {export_path}")
            return True
        except Exception as e:
            logger.error(f"导出报告失败: {str(e)}")
            return False


# 调用示例
if __name__ == "__main__":
    # 初始化API客户端
    APP_KEY = "your_jd_app_key"
    APP_SECRET = "your_jd_app_secret"
    ACCESS_TOKEN = "your_jd_access_token"
    
    api = JDProductDetailAPI(APP_KEY, APP_SECRET, ACCESS_TOKEN)
    
    # 目标商品SKU ID(可从商品详情页URL获取)
    TARGET_SKU_IDS = ["100012345678", "100009876543"]  # 示例SKU ID
    
    try:
        # 1. 获取商品详情(包含价格历史)
        print("===== 开始获取商品详情 =====")
        products = api.get_product_details(
            TARGET_SKU_IDS,
            area="北京",
            platform=2,  # APP端
            need_history=True
        )
        
        print(f"成功获取 {len(products)} 个商品详情")
        
        # 2. 对第一个商品进行深度分析
        if products:
            product = products[0]
            print(f"\n===== 开始分析商品: {product['name']} =====")
            
            # 2.1 价格趋势预测
            price_prediction = api.predict_price_trend(product["sku_id"])
            print("\n未来7天价格预测:")
            for pred in price_prediction[:3]:  # 只显示前3天
                print(f"   {pred['date']}: ¥{pred['predicted_price']}")
            
            # 2.2 最优购买策略分析
            buy_strategy = api.analyze_best_buying_strategy(product["sku_id"], quantity=2)
            print("\n最优购买策略:")
            print(f"   方案: {buy_strategy['best_strategy']['strategy']}")
            print(f"   总价: ¥{buy_strategy['best_strategy']['total_price']}")
            print(f"   单价: ¥{buy_strategy['best_strategy']['per_unit']}")
            print(f"   预计节省: ¥{buy_strategy['estimated_savings']}")
            
            # 2.3 用户偏好匹配(模拟用户画像)
            user_profile = {
                "preferred_brands": ["华为", "小米", "苹果"],
                "price_range": [0, 5000],
                "min_positive_ratio": 95,
                "like_promotion": True,
                "interested_categories": ["手机", "数码"],
                "need_after_sale": True
            }
            
            match_result = api.match_user_preferences(product, user_profile)
            print("\n用户偏好匹配:")
            print(f"   匹配得分: {match_result['match_score']}分")
            print("   匹配原因:")
            for reason in match_result["match_reasons"]:
                print(f"      - {reason}")
            print("   购买建议:")
            for suggestion in match_result["suggestions"]:
                print(f"      - {suggestion}")
            
            # 2.4 导出分析报告
            export_path = f"jd_product_analysis_{product['sku_id']}.xlsx"
            if api.export_product_analysis(product, buy_strategy, export_path):
                print(f"\n分析报告已导出至: {export_path}")
                
    except Exception as e:
        print(f"执行出错: {str(e)}")

五、技术亮点与商业应用

本方案与常规实现的核心差异体现在三个维度:

  1. 智能价格分析系统

    • 动态价格追踪:通过历史价格数据构建价格波动模型,预测未来 7 天价格趋势
    • 区域价格对比:支持多地区价格查询,识别区域价格差异(最高可达 30%)
    • 价格敏感度评分:结合折扣力度与促销频率,量化商品价格弹性
  2. 促销规则解码引擎

    • 多维度促销解析:自动识别并解析优惠券、满减、多件折扣等 12 种促销类型
    • 最优组合算法:计算促销叠加方案,最高可提升优惠力度 40%
    • 购买量优化建议:根据促销规则推荐最优购买数量,避免多买浪费
  3. 用户 - 商品匹配系统

    • 多维度匹配算法:从品牌偏好、价格敏感度、品类兴趣等 6 个维度计算匹配度
    • 智能购买建议:结合库存状态、价格趋势生成个性化购买时机建议
    • 决策辅助报告:自动生成包含 15 项关键指标的 Excel 分析报告

六、使用说明与扩展建议

  • 环境依赖:Python 3.8+,需安装requestspandasscikit-learntqdm库(pip install requests pandas scikit-learn tqdm
  • 权限获取:登录京东开放平台(open.jd.com),注册开发者账号并申请jd.union.open.goods.detail.query接口权限
  • SKU ID 获取:从商品详情页 URL 提取(如https://item.jd.com/100012345678.html中的100012345678即为 SKU ID)

扩展方向:

  1. 竞品分析系统:扩展代码支持同时分析多个竞品,生成竞争力对比报告
  2. 库存预警机制:监控商品库存变化,当库存低于阈值时自动发送提醒
  3. 智能导购机器人:结合 NLP 技术,实现基于商品分析的智能客服功能

该方案特别适合电商数据分析人员、价格监测系统开发者、个性化推荐系统构建者等用户,通过技术手段深度挖掘商品数据价值,优化采购决策与销售策略。

相关推荐
盒马coding3 小时前
PostgresWAL文件和序列号
数据库·oracle
xhbh6663 小时前
【实战避坑】MySQL自增主键(AUTO_INCREMENT)全解:从锁机制、间隙问题到分库分表替代方案
android·数据库·mysql·mysql自增主键
帅帅梓3 小时前
docker网络
网络·docker·php
hh真是个慢性子3 小时前
mongodb慢查询优化 速度欻欻滴~
数据库·mongodb·性能优化·慢查询
色空大师4 小时前
【MongoDB的RLE压缩数据存储】
数据库·mongodb
安当加密4 小时前
通过TDE透明加密实现人大金仓数据库的免改造存储加密方案
数据库·金仓·透明加密
养生技术人4 小时前
Oracle OCP认证考试题目详解082系列第49题
运维·数据库·sql·oracle·database·开闭原则·ocp
white-persist4 小时前
SQL 注入详解:从原理到实战
前端·网络·数据库·sql·安全·web安全·原型模式
Databend4 小时前
Raft 中的 IO 执行顺序:内存状态与持久化状态的陷阱
数据库