要利用淘宝开放API接口监控商品状态,需遵循以下步骤实现:
一、前期准备
-
注册开发者账号
访问淘宝开放平台,使用淘宝账号登录并完成实名认证(个人需绑定支付宝,企业需提交营业执照)。
-
创建应用并获取权限
- 进入控制台 > 应用管理 > 创建应用,填写应用名称、类型(自用型/他用型)及场景描述。
- 在API权限管理中申请所需接口权限(如
taobao.item.get
、taobao.item.price.get
)。 - 审核通过后,获取
App Key
和App Secret
(调用API的凭证)。
-
环境配置
- 安装Python依赖库:
pip install requests hashlib
。 - 准备商品ID列表(需监控的商品
num_iid
)。
- 安装Python依赖库:
二、核心代码实现
1. 签名生成与API调用
python
|-------------------------------------------------------------------------------------------------|
| import requests
|
| import hashlib
|
| import time
|
| |
| 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):
|
| sorted_params = sorted(params.items(), key=lambda x: x[0])
|
| sign_str = self.app_secret + ''.join([f"{k}{v}" for k, v in sorted_params]) + self.app_secret
|
| return hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper()
|
| |
| def call_api(self, method, 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
|-----------------------------------------------------------------------------------------------------------|
| def get_item_info(api, item_id):
|
| params = {
|
| "num_iid": item_id,
|
| "fields": "num_iid,title,price,num,pic_url,sku"
|
| }
|
| result = api.call_api("taobao.item.get", params)
|
| if "item_get_response" in result and "item" in result["item_get_response"]:
|
| return result["item_get_response"]["item"]
|
| else:
|
| print(f"Error fetching item {item_id}: {result.get('error_response', {}).get('msg', 'Unknown error')}")
|
| return None
|
3. 监控逻辑与数据存储
python
|------------------------------------------------------------------------------------|
| import json
|
| import time
|
| from datetime import datetime
|
| |
| # 初始化API客户端
|
| api = TaobaoAPI(app_key="YOUR_APP_KEY", app_secret="YOUR_APP_SECRET")
|
| |
| # 监控商品列表(示例)
|
| monitored_items = {
|
| "1234567890": {"last_price": None, "last_stock": None}, # 商品ID: 初始状态
|
| "0987654321": {"last_price": None, "last_stock": None}
|
| }
|
| |
| def monitor_items():
|
| while True:
|
| for item_id, state in monitored_items.items():
|
| item_info = get_item_info(api, item_id)
|
| if item_info:
|
| current_price = item_info.get("price")
|
| current_stock = item_info.get("num")
|
| |
| # 状态变化检测
|
| if state["last_price"] != current_price or state["last_stock"] != current_stock:
|
| print(f"[{datetime.now()}] 商品 {item_id} 状态变化:")
|
| print(f" 价格: {state['last_price']} → {current_price}")
|
| print(f" 库存: {state['last_stock']} → {current_stock}")
|
| |
| # 更新状态
|
| state["last_price"] = current_price
|
| state["last_stock"] = current_stock
|
| |
| # 可选:触发通知(邮件/短信)
|
| # send_notification(item_id, current_price, current_stock)
|
| |
| time.sleep(60) # 每分钟检查一次
|
| |
| if __name__ == "__main__":
|
| monitor_items()
|
三、进阶功能扩展
-
通知机制
集成邮件或短信服务(如阿里云短信),当检测到状态变化时发送通知:
python
|---------------------------------------------------------|
|def send_notification(item_id, price, stock):
|
|# 示例:使用SMTP发送邮件
|
|msg = f"商品 {item_id} 价格更新为 {price} 元,库存剩余 {stock} 件。"
|
|# 实际代码需配置SMTP服务器及收件人信息
|
|print(f"Sending notification: {msg}")
| -
数据持久化存储
将历史数据存入MySQL或Redis,便于分析趋势:
python
|------------------------------------------------------------------------------------------------------|
|import redis
|
| |
|r = redis.Redis(host='localhost', port=6379, db=0)
|
| |
|def save_to_redis(item_id, price, stock):
|
|r.hset(f"item:{item_id}", "price", price, "stock", stock, "timestamp", datetime.now().isoformat())
| -
批量监控优化
使用多线程或异步请求提高效率(示例使用
concurrent.futures
):python
|------------------------------------------------------------------------------------|
|from concurrent.futures import ThreadPoolExecutor
|
| |
|def batch_monitor(item_ids):
|
|with ThreadPoolExecutor(max_workers=5) as executor:
|
|futures = [executor.submit(get_item_info, api, item_id) for item_id in item_ids]
|
|for future in futures:
|
|print(future.result())
|
四、注意事项
- 频率限制:淘宝API对调用次数有限制(基础权限每日1000次),需合理设置检查间隔(建议1-5分钟)。
- 数据准确性:部分数据(如库存)可能存在延迟,建议结合订单状态综合判断。
- 合规性:禁止爬取用户隐私数据,确保数据使用符合开放平台-文档中心。
通过以上步骤,可实现一个基础的商品状态监控系统,实时掌握价格、库存等关键信息的变化。