获取淘宝店铺的所有商品信息是电商开发中的常见需求,通过 API 接口可以高效地实现店铺商品的同步、分析与管理。以下是完整的接口调用示例及实现方案:
一、接口选择与权限申请
1. 核心接口介绍
获取店铺商品的主要接口是taobao.shop.get
和taobao.items.onsale.get
:
taobao.shop.get
:获取店铺基本信息(含店铺 ID)taobao.items.onsale.get
:获取店铺在售商品列表
2. 权限申请流程
-
登录淘宝开放平台
-
创建应用并完成实名认证
-
申请以下权限:
taobao.shop.get
(基础权限,可直接申请)taobao.items.onsale.get
(需提交应用场景审核)
-
获取 AppKey 和 AppSecret
二、完整代码示例(Python)
1. 基础 API 调用类
python
import hashlib
import time
import requests
import json
import math
class TaobaoAPI:
def __init__(self, app_key, app_secret):
self.app_key = app_key
self.app_secret = app_secret
self.api_url = "https://eco.taobao.com/router/rest"
def generate_sign(self, params):
"""生成API签名(MD5算法)"""
sorted_params = sorted(params.items(), key=lambda x: x[0])
sign_str = self.app_secret
for k, v in sorted_params:
sign_str += f"{k}{v}"
sign_str += self.app_secret
return hashlib.md5(sign_str.encode()).hexdigest().upper()
def call(self, method, params=None):
"""通用API调用方法"""
if params is None:
params = {}
# 公共参数
common_params = {
"app_key": self.app_key,
"method": method,
"format": "json",
"v": "2.0",
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
"sign_method": "md5"
}
# 合并参数
all_params = {**common_params, **params}
# 生成签名
all_params["sign"] = self.generate_sign(all_params)
# 发送请求
response = requests.get(self.api_url, params=all_params)
return response.json()
2. 获取店铺信息及商品列表
python
class TaobaoShopAPI(TaobaoAPI):
def get_shop_info(self, seller_nick):
"""根据卖家昵称获取店铺信息"""
method = "taobao.shop.get"
params = {
"seller_nick": seller_nick
}
result = self.call(method, params)
return result
def get_shop_items(self, seller_id, page_no=1, page_size=40):
"""获取店铺在售商品列表"""
method = "taobao.items.onsale.get"
params = {
"seller_id": seller_id,
"page_no": page_no,
"page_size": page_size,
"fields": "num_iid,title,price,pic_url,item_desc,seller_cids"
}
result = self.call(method, params)
return result
def get_all_shop_items(self, seller_nick, page_size=40):
"""获取店铺所有在售商品(自动处理分页)"""
# 1. 获取店铺ID
shop_result = self.get_shop_info(seller_nick)
if "error_response" in shop_result:
print(f"获取店铺信息失败: {shop_result['error_response']['msg']}")
return []
seller_id = shop_result["shop_get_response"]["shop"]["seller_id"]
print(f"店铺ID: {seller_id}")
# 2. 获取总商品数
first_page = self.get_shop_items(seller_id, page_no=1, page_size=1)
if "error_response" in first_page:
print(f"获取商品列表失败: {first_page['error_response']['msg']}")
return []
total_results = first_page["items_onsale_get_response"]["total_results"]
if total_results == 0:
print("该店铺没有在售商品")
return []
# 3. 计算总页数
total_pages = math.ceil(total_results / page_size)
print(f"店铺共有 {total_results} 个商品,共 {total_pages} 页")
# 4. 分页获取所有商品
all_items = []
for page in range(1, total_pages + 1):
print(f"正在获取第 {page}/{total_pages} 页...")
page_result = self.get_shop_items(seller_id, page, page_size)
if "items" in page_result["items_onsale_get_response"]:
items = page_result["items_onsale_get_response"]["items"]["item"]
all_items.extend(items)
# 避免频繁调用触发限流
time.sleep(1)
print(f"成功获取 {len(all_items)} 个商品")
return all_items
3. 示例调用与结果处理
# 使用示例
if __name__ == "__main__":
# 替换为你的AppKey和AppSecret
app_key = "你的AppKey"
app_secret = "你的AppSecret"
# 替换为目标店铺的卖家昵称
seller_nick = "示例店铺"
# 初始化API
api = TaobaoShopAPI(app_key, app_secret)
# 获取店铺所有商品
all_items = api.get_all_shop_items(seller_nick)
# 处理结果(示例:保存到JSON文件)
if all_items:
with open(f"shop_{seller_nick}_items.json", "w", encoding="utf-8") as f:
json.dump(all_items, f, ensure_ascii=False, indent=2)
print(f"已保存商品数据到 shop_{seller_nick}_items.json")
# 示例:统计商品价格分布
prices = [float(item["price"]) for item in all_items]
avg_price = sum(prices) / len(prices)
max_price = max(prices)
min_price = min(prices)
print(f"商品价格统计 - 平均: {avg_price:.2f}元, 最高: {max_price:.2f}元, 最低: {min_price:.2f}元")
三、接口响应数据解析
1. 店铺信息响应示例
json
{
"shop_get_response": {
"shop": {
"shop_id": 123456789,
"seller_id": 987654321,
"seller_nick": "示例店铺",
"shop_name": "示例品牌官方店",
"shop_url": "https://shop123456789.taobao.com",
"main_image": "https://img.alicdn.com/shop.jpg",
"create_time": "2020-01-01 12:00:00",
"modify_time": "2025-07-01 10:00:00",
"description": "专注于高品质商品销售...",
"shop_score": {
"score_item": [
{"rate": 4.9, "type": "item"}, # 描述相符
{"rate": 4.8, "type": "service"}, # 服务态度
{"rate": 4.9, "type": "delivery"} # 物流服务
]
}
}
}
}
2. 商品列表响应示例
{
"items_onsale_get_response": {
"total_results": 100,
"items": {
"item": [
{
"num_iid": 112233445566,
"title": "2025新款夏季纯棉T恤 男女同款",
"price": "79.00",
"original_price": "99.00",
"pic_url": "https://img.alicdn.com/item.jpg",
"item_desc": "优质纯棉面料...",
"seller_cids": "16,160", # 卖家自定义类目
"props": [
{"name": "颜色", "value": "白色,黑色,灰色"},
{"name": "尺码", "value": "S,M,L,XL"}
],
"sell_count": 1234, # 30天销量
"comment_count": 567, # 评论数
"is_taobao": true, # 是否为淘宝商品(非天猫)
"shop_id": 123456789
},
{
"num_iid": 223344556677,
"title": "真皮休闲运动鞋 透气轻便",
"price": "199.00",
"pic_url": "https://img.alicdn.com/item2.jpg",
"sell_count": 890,
"shop_id": 123456789
}
]
}
}
}
四、关键技术要点
1. 分页处理策略
taobao.items.onsale.get
接口默认每页返回 40 条数据- 通过
total_results
字段获取总商品数,计算总页数 - 建议每次请求间隔 1-2 秒,避免触发频率限制
2. 频率限制与异常处理
-
新开发者默认调用限制:200 次 / 天
-
常见错误码处理:
40001
:缺少必选参数 → 检查参数完整性40003
:权限不足 → 确认权限申请状态41001
:频率限制 → 增加请求间隔或申请更高配额
3. 数据缓存优化
python
运行
import redis
import time
class CachedTaobaoAPI(TaobaoShopAPI):
def __init__(self, app_key, app_secret, redis_host="localhost", redis_port=6379):
super().__init__(app_key, app_secret)
self.redis_client = redis.Redis(host=redis_host, port=redis_port)
def call(self, method, params=None):
"""带缓存的API调用"""
if params is None:
params = {}
# 生成缓存键
cache_key = f"taobao_api:{method}:{json.dumps(params, sort_keys=True)}"
# 检查缓存(有效期2小时)
cached_result = self.redis_client.get(cache_key)
if cached_result:
return json.loads(cached_result)
# 无缓存,调用API
result = super().call(method, params)
# 缓存结果
self.redis_client.setex(cache_key, 7200, json.dumps(result))
return result
五、应用场景扩展
-
店铺商品同步系统:
- 定时同步店铺商品到自有平台
- 监控商品价格、库存变化并预警
-
竞品分析工具:
- 批量获取竞品店铺商品数据
- 分析价格策略、销售情况和用户评价
-
选品推荐系统:
- 基于店铺商品数据生成选品建议
- 结合销售数据和市场趋势优化推荐算法
-
商品信息管理:
- 批量导出商品信息用于数据分析
- 自动生成商品详情页或营销素材
通过以上示例,开发者可以快速实现淘宝店铺商品的获取与管理功能。在实际应用中,建议根据业务需求增加数据清洗、异步处理和可视化展示等功能,提升系统的实用性和效率。同时,注意遵守淘宝开放平台的使用规范,确保数据使用的合法性。