淘宝开放平台的item_get接口是获取商品详情的核心工具,广泛应用于电商分析、比价系统、商品监控等场景。本文将从接口基础、对接流程、高级技巧到最佳实践,全面讲解如何高效对接该接口。
一、接口基础认知
二、对接前置准备
三、接口调用流程
四、代码实现示例(Python)
import requests
import hashlib
import time
import json
class TaobaoItemApi:
def __init__(self, app_key, app_secret):
self.app_key = app_key
self.app_secret = app_secret
self.url = "https://eco.taobao.com/router/rest"
def generate_sign(self, params):
"""生成签名"""
# 按参数名ASCII排序
sorted_params = sorted(params.items(), key=lambda x: x[0])
# 拼接参数
sign_str = self.app_secret
for key, value in sorted_params:
sign_str += f"{key}{value}"
sign_str += self.app_secret
# MD5加密并转为大写
sign = hashlib.md5(sign_str.encode()).hexdigest().upper()
return sign
def item_get(self, num_iid, fields="title,price,pics,detail_url"):
"""获取商品详情"""
params = {
"app_key": self.app_key,
"method": "taobao.item.get",
"format": "json",
"v": "2.0",
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"num_iid": num_iid,
"fields": fields
}
# 生成签名
params["sign"] = self.generate_sign(params)
try:
response = requests.get(self.url, params=params, timeout=10)
result = json.loads(response.text)
# 处理错误
if "error_response" in result:
error = result["error_response"]
return {"success": False, "error_code": error["code"], "error_msg": error["msg"]}
return {"success": True, "data": result["item_get_response"]["item"]}
except Exception as e:
return {"success": False, "error_msg": str(e)}
# 使用示例
if __name__ == "__main__":
# 替换为自己的app_key和app_secret
APP_KEY = "your_app_key"
APP_SECRET = "your_app_secret"
api = TaobaoItemApi(APP_KEY, APP_SECRET)
# 调用接口,获取商品ID为123456的详情
result = api.item_get("123456")
if result["success"]:
print("商品标题:", result["data"]["title"])
print("商品价格:", result["data"]["price"])
print("商品图片:", result["data"]["pics"])
else:
print("获取失败:", result["error_msg"])