Diablo Edit2:暗黑破坏神2角色编辑器终极指南
2026/5/5 10:51:39
基于 Python 实现淘宝商品详情(含主图)API 接口调用的完整方案,包含接口接入、数据解析、异常处理等核心内容。
注意:淘宝官方 API 需通过阿里开放平台申请权限,本文以通用开放接口为例,实际使用需遵循平台规范。
AppKey、AppSecret。taobao.item.get(商品详情)接口权限(需审核)。bash
运行
pip install requests hmac hashlib urllib.parse # 核心依赖 pip install python-dotenv # 可选,管理环境变量env
APP_KEY=你的AppKey APP_SECRET=你的AppSecretpython
运行
import requests import time import hmac import hashlib import urllib.parse from dotenv import load_dotenv # 若不用.env可删除 import os # 加载环境变量(可选) load_dotenv() class TaobaoItemAPI: """淘宝商品详情API调用类""" def __init__(self, app_key, app_secret): self.app_key = app_key self.app_secret = app_secret self.gateway_url = "https://eco.taobao.com/router/rest" # 正式环境网关 # 沙箱环境网关:https://gw.api.tbsandbox.com/router/rest def _generate_sign(self, params): """生成API签名(淘宝签名规则)""" # 1. 按参数名升序排序 sorted_params = sorted(params.items(), key=lambda x: x[0]) # 2. 拼接成key=value格式 sign_str = "" for k, v in sorted_params: if v: # 空值不参与签名 sign_str += f"{k}{v}" # 3. 拼接AppSecret并加密 sign_str = self.app_secret + sign_str + self.app_secret sign = hmac.new( self.app_secret.encode("utf-8"), sign_str.encode("utf-8"), hashlib.md5 ).hexdigest().upper() return sign def get_item_detail(self, num_iid, fields=None): """ 获取商品详情(含主图) :param num_iid: 商品ID(必填) :param fields: 需要返回的字段,默认返回核心字段 :return: 解析后的商品详情字典 """ # 默认返回字段(可根据需求扩展) if not fields: fields = ( "num_iid,title,pic_url,price,orginal_price,detail_url," "item_imgs,cat_name,brand_name,sell_count,stock" ) # 构造请求参数 params = { "method": "taobao.item.get", # 接口名称 "app_key": self.app_key, "format": "json", "v": "2.0", "timestamp": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "sign_method": "md5", "num_iid": num_iid, "fields": fields } # 生成签名 params["sign"] = self._generate_sign(params) try: # 发送请求 response = requests.get( self.gateway_url, params=params, timeout=10, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"} ) response.raise_for_status() # 抛出HTTP异常 result = response.json() # 处理接口返回 if "error_response" in result: raise Exception(f"接口错误:{result['error_response']['msg']}") item = result["item_get_response"]["item"] return { "商品ID": item["num_iid"], "商品标题": item["title"], "商品主图": item["pic_url"], "商品价格": item["price"], "原价": item["orginal_price"], "商品链接": item["detail_url"], "销量": item.get("sell_count", 0), "库存": item.get("stock", 0), "分类名称": item.get("cat_name", ""), "品牌名称": item.get("brand_name", ""), "商品图片列表": [img["url"] for img in item.get("item_imgs", [])] } except requests.exceptions.RequestException as e: raise Exception(f"网络请求错误:{str(e)}") except Exception as e: raise Exception(f"获取商品详情失败:{str(e)}") # 示例调用 if __name__ == "__main__": # 初始化API实例 api = TaobaoItemAPI( app_key=os.getenv("APP_KEY"), # 或直接填写你的AppKey app_secret=os.getenv("APP_SECRET") # 或直接填写你的AppSecret ) # 调用接口(替换为实际商品ID) try: item_detail = api.get_item_detail(num_iid="1234567890") print("商品详情:") for key, value in item_detail.items(): print(f"{key}: {value}") # 单独获取主图 main_image_url = item_detail["商品主图"] print(f"\n商品主图URL:{main_image_url}") # 下载主图(可选) img_response = requests.get(main_image_url, timeout=10) with open("taobao_item_main_img.jpg", "wb") as f: f.write(img_response.content) print("主图已下载到本地:taobao_item_main_img.jpg") except Exception as e: print(f"错误:{str(e)}")| 参数名 | 必选 | 说明 |
|---|---|---|
| num_iid | 是 | 商品 ID(淘宝商品链接中的 ID,如 |
| fields | 否 | 需要返回的字段,可参考淘宝开放平台文档 |
淘宝 API 签名生成步骤:
key1value1key2value2格式;AppSecret,用 MD5 加密后转大写即为 sign。taobao.item.get接口权限,且账号未被限流;get_item_detail方法,注意添加延时避免限流;tenacity库),处理临时网络错误。