×

淘宝item_search_similar - 搜索相似的商品API接口,用python返回数据

万邦科技Lex 万邦科技Lex 发表于2025-08-24 16:06:28 浏览260 评论0

抢沙发发表评论

     免费测试淘宝API接口

淘宝联盟开放平台中,与 “搜索相似商品” 相关的官方接口是(物料优选接口),可通过商品 ID 或图片等物料获取相似推荐商品。虽然没有直接命名为item_search_similar的接口,但该接口可实现类似功能.

以下是基于该接口的 Python 实现,用于根据商品 ID 搜索相似商品并返回数据:

import requests

import hashlib

import time

import json

import logging

from typing import List, Dict, Optional


# 配置日志

logging.basicConfig(

    level=logging.INFO,

    format="%(asctime)s - %(levelname)s - %(message)s"

)


class TaobaoSimilarItemsAPI:

    def __init__(self, appkey: str, appsecret: str, adzone_id: str):

        """

        初始化淘宝相似商品搜索API客户端

        :param appkey: 淘宝联盟应用appkey

        :param appsecret: 淘宝联盟应用appsecret

        :param adzone_id: 推广位ID(需提前创建)

        """

        self.appkey = appkey

        self.appsecret = appsecret

        self.adzone_id = adzone_id

        self.base_url = "https://eco.taobao.com/router/rest"

        self.session = requests.Session()


    def _generate_sign(self, params: Dict) -> str:

        """生成淘宝API签名"""

        # 1. 按参数名ASCII升序排序

        sorted_params = sorted(params.items(), key=lambda x: x[0])

        # 2. 拼接为key=value格式

        sign_str = "".join([f"{k}{v}" for k, v in sorted_params])

        # 3. 首尾拼接appsecret并MD5加密

        sign_str = self.appsecret + sign_str + self.appsecret

        return hashlib.md5(sign_str.encode()).hexdigest().upper()


    def _get_timestamp(self) -> str:

        """生成时间戳(yyyy-MM-dd HH:mm:ss)"""

        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


    def search_similar_items(self, num_iid: str, page: int = 1, page_size: int = 20) -> Optional[List[Dict]]:

        """

        搜索相似商品

        :param num_iid: 参考商品ID

        :param page: 页码

        :param page_size: 每页数量(最大20)

        :return: 相似商品列表

        """

        # 接口参数

        params = {

            "method": "taobao.tbk.dg.optimus.material",

            "app_key": self.appkey,

            "timestamp": self._get_timestamp(),

            "format": "json",

            "v": "2.0",

            "sign_method": "md5",

            "adzone_id": self.adzone_id,

            "material_id": num_iid,  # 参考商品ID

            "material_type": "item",  # 物料类型为商品

            "page": page,

            "page_size": page_size

        }


        # 生成签名

        params["sign"] = self._generate_sign(params)


        try:

            # 发送请求

            response = self.session.get(

                self.base_url,

                params=params,

                timeout=15

            )

            response.raise_for_status()

            result = response.json()


            # 处理错误响应

            if "error_response" in result:

                error = result["error_response"]

                logging.error(f"接口错误:{error['msg']}(错误码:{error['code']})")

                return None


            # 解析商品数据

            material_response = result.get("tbk_dg_optimus_material_response", {})

            item_list = material_response.get("result_list", {}).get("map_data", [])


            # 格式化返回结果

            formatted_items = []

            for item in item_list:

                formatted_items.append({

                    "num_iid": item.get("num_iid"),  # 商品ID

                    "title": item.get("title"),  # 商品标题

                    "pict_url": item.get("pict_url"),  # 商品主图

                    "price": float(item.get("reserve_price", 0)),  # 原价

                    "final_price": float(item.get("zk_final_price", 0)),  # 优惠价

                    "sales": int(item.get("sales", 0)),  # 销量

                    "commission_rate": float(item.get("commission_rate", 0)) / 100,  # 佣金比例(%)

                    "shop_title": item.get("shop_title"),  # 店铺名称

                    "shop_type": "天猫" if item.get("user_type") == 1 else "淘宝",  # 店铺类型

                    "provcity": item.get("provcity"),  # 产地

                    "coupon_info": item.get("coupon_info")  # 优惠券信息

                })


            logging.info(f"找到{len(formatted_items)}个相似商品(页码:{page})")

            return formatted_items


        except Exception as e:

            logging.error(f"请求异常:{str(e)}")

            return None



# 示例调用

if __name__ == "__main__":

    # 替换为实际参数(从淘宝联盟开放平台获取)

    APPKEY = "your_appkey"

    APPSECRET = "your_appsecret"

    ADZONE_ID = "your_adzone_id"  # 推广位ID

    REFERENCE_ITEM_ID = "6543217890"  # 参考商品ID(用于搜索相似商品)


    # 初始化客户端

    api = TaobaoSimilarItemsAPI(APPKEY, APPSECRET, ADZONE_ID)

    

    # 搜索相似商品(第1页,20条/页)

    similar_items = api.search_similar_items(

        num_iid=REFERENCE_ITEM_ID,

        page=1,

        page_size=20

    )

    

    if similar_items:

        print(f"参考商品ID:{REFERENCE_ITEM_ID} 的相似商品:\n")

        for i, item in enumerate(similar_items[:5], 1):  # 打印前5条

            print(f"{i}. {item['title']}")

            print(f"   价格:{item['price']}元 → 优惠价:{item['final_price']}元")

            print(f"   销量:{item['sales']}件 | 佣金:{item['commission_rate']*100}%")

            print(f"   店铺:{item['shop_title']}({item['shop_type']})")

            if item['coupon_info']:

                print(f"   优惠:{item['coupon_info']}")

            print("-" * 80)

代码说明

  1. 接口选择:使用淘宝联盟的taobao.tbk.dg.optimus.material接口,通过material_id(商品 ID)和material_type=item参数获取相似商品推荐。
  2. 核心参数
    • appkeyappsecret:淘宝联盟开发者账号的应用密钥

    • adzone_id:推广位 ID,需在淘宝联盟后台创建

    • material_id:参考商品的 ID,用于搜索相似商品

  3. 返回数据字段
    • 基本信息:商品 ID、标题、主图 URL

    • 价格信息:原价、优惠价、佣金比例

    • 店铺信息:店铺名称、类型(淘宝 / 天猫)、产地

    • 销售信息:销量、优惠券信息

  4. 使用注意事项
    • 需要先在淘宝联盟开放平台注册并创建应用

    • 接口有调用频率限制(通常 QPS=10)

    • 返回的是参与淘宝客推广的商品,非全平台商品

    • 部分字段(如优惠券)可能为空,需做容错处理

扩展建议

  • 可增加代理 IP 池应对反爬限制

  • 实现分页遍历功能获取更多相似商品

  • 加入缓存机制减少重复请求

  • 增加商品相似度评分排序功能


使用时请遵守淘宝联盟的 API 使用规范,避免过度调用或用于不正当用途。

群贤毕至

访客