以下是关于使用淘宝API批量获取商品信息的实战指南,涵盖技术实现与注意事项:
一、准备工作
- 注册淘宝开放平台账号
- 访问淘宝开放平台/万邦开放平台
- 完成企业/个人开发者认证(需营业执照或个人身份证)
- 创建应用获取权限
- 进入「控制台」→「应用管理」→「创建应用」
- 必选API权限:
- 淘宝客-商品查询(taobao.tbk.item.get)
- 商品搜索(taobao.items.search)
- 提交审核后获取:
- AppKey(应用标识)
- AppSecret(应用密钥)
- 环境要求python
pip install requests |
pip install hashlib |
二、API调用核心代码(Python示例)
python
import requests |
import hashlib |
import time |
import urllib.parse |
|
class TaobaoAPI: |
def __init__(self, appkey, appsecret): |
self.appkey = appkey |
self.appsecret = appsecret |
self.base_url = "https://eco.taobao.com/router/rest" |
|
def generate_sign(self, params): |
sorted_params = sorted(params.items()) |
query_string = ''.join([f"{k}{v}" for k, v in sorted_params if v != '']) |
raw = self.appsecret + query_string + self.appsecret |
return hashlib.md5(raw.encode('utf-8')).hexdigest().upper() |
|
def call_api(self, method, fields): |
timestamp = str(int(time.time())) |
params = { |
'method': method, |
'app_key': self.appkey, |
'sign_method': 'md5', |
'timestamp': timestamp, |
'format': 'json', |
'v': '2.0', |
**fields |
} |
params['sign'] = self.generate_sign(params) |
|
response = requests.get(self.base_url, params=params) |
return response.json() |
|
# 初始化客户端 |
client = TaobaoAPI( |
appkey='YOUR_APPKEY', |
appsecret='YOUR_APPSECRET' |
) |
|
# 批量获取商品示例 |
def batch_fetch_items(keywords, page_size=40, max_pages=10): |
all_items = [] |
for page in range(1, max_pages+1): |
params = { |
'q': keywords, |
'page_no': page, |
'page_size': page_size |
} |
result = client.call_api('taobao.items.search', params) |
|
if result.get('error_response'): |
print(f"Error: {result['error_response']['sub_msg']}") |
break |
|
items = result.get('items_search_response', {}).get('items', {}).get('item', []) |
if not items: |
break |
|
all_items.extend(items) |
time.sleep(1) # 遵守API频率限制 |
return all_items |
|
# 使用示例 |
products = batch_fetch_items('运动鞋', page_size=40, max_pages=5) |
for p in products[:10]: # 仅展示前10条 |
print(f"{p['title']} - ¥{p['price']} - 销量:{p['volume']}") |
三、关键参数说明
参数 | 说明 | 示例值 |
---|
q | 搜索关键词 | "无线蓝牙耳机" |
page_no | 页码(1-100) | 1 |
page_size | 每页数量(1-40) | 40 |
sort | 排序方式 | "sale-desc"(销量降序) |
is_tmall | 是否仅天猫商品 | "true" |
start_price | 价格下限(单位:分) | 10000(即100元) |
end_price | 价格上限 | 500000(即5000元) |
四、数据解析技巧
python
# 提取核心字段 |
for item in products: |
data = { |
'title': item['title'], |
'price': float(item['price'])/100, # 转换为元 |
'sales': int(item['volume']), |
'detail_url': item['detail_url'], |
'pic_url': item['pic_url'] + '_400x400.jpg', # 获取高清图 |
'shop_name': item['nick'] |
} |
# 存储到CSV/数据库 |
五、注意事项
- 频率限制
- 免费版:QPS≤1(每秒1次)
- 建议设置
time.sleep(1)
避免触发限流
- 数据合规
- 禁止存储用户隐私数据(如手机号、地址)
- 不得直接展示商品价格,需通过淘宝客链接跳转
- 反爬机制
- 随机User-Agent
- 使用代理IP池(高频需求时)
- 高级功能
params['adzone_id'] = '你的PID' |
- 商品详情API(需单独申请):
taobao.item.get
六、常见问题解决
- 签名错误
- 检查参数排序是否按ASCII顺序
- 确认AppSecret正确性
- 返回空数据
- IP被封禁
建议优先使用淘宝官方提供的淘宝开放API文档进行深度开发。对于高频商业需求,可考虑购买淘宝开放平台的增值服务(如VIP接口)。