App Key和
App Secret(调用API的凭证)。taobao.items.onsale.get接口权限:
taobao.item.get:获取单个商品详情(如库存、SKU)。taobao.shop.get:获取店铺基本信息(如店铺ID)。bashpip install requests hashlib pandas
pythonimport requestsimport hashlibimport timeimport mathclass TaobaoAPI:def __init__(self, app_key, app_secret):self.app_key = app_keyself.app_secret = app_secretself.api_url = "https://eco.taobao.com/router/rest"def generate_sign(self, params):"""生成MD5签名"""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_secretreturn hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper()def call_api(self, method, params):"""通用API调用方法"""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()
pythonclass TaobaoShopAPI(TaobaoAPI):def get_shop_info(self, seller_nick):"""根据卖家昵称获取店铺ID"""method = "taobao.shop.get"params = {"seller_nick": seller_nick}result = self.call_api(method, params)if "shop_get_response" in result and "shop" in result["shop_get_response"]:return result["shop_get_response"]["shop"]["seller_id"]else:raise Exception(f"获取店铺ID失败: {result.get('error_response', {}).get('msg', '未知错误')}")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,num,pic_url,sold_quantity,seller_cids"}return self.call_api(method, params)def get_all_shop_items(self, seller_nick, page_size=40):"""获取店铺所有在售商品(自动处理分页)"""# 1. 获取店铺IDseller_id = self.get_shop_info(seller_nick)print(f"店铺ID: {seller_id}")# 2. 获取总商品数first_page = self.get_shop_items(seller_id, page_no、=1, page_size=1)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_onsale_get_response" in page_result and "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
pythonif __name__ == "__main__":# 配置参数app_key = "YOUR_APP_KEY"app_secret = "YOUR_APP_SECRET"seller_nick = "YOUR_SELLER_NICK" # 店铺昵称(如"淘宝官方旗舰店")# 初始化API客户端api = TaobaoShopAPI(app_key, app_secret)try:# 获取所有商品items = api.get_all_shop_items(seller_nick)# 打印前3条商品信息print("前3条商品信息:")for item in items[:3]:print(f"商品ID: {item['num_iid']}, 标题: {item['title']}, 价格: {item['price']}, 库存: {item['num']}, 销量: {item['sold_quantity']}")# 可选:保存到CSV文件import pandas as pddf = pd.DataFrame(items)df.to_csv("shop_items.csv", index=False, encoding='utf-8-sig')except Exception as e:print(f"错误: {e}")
保存到MySQL:
使用
pymysql库将数据存入数据库,便于查询和分析。
pythonimport pymysqldef save_to_mysql(items):conn = pymysql.connect(host='localhost', user='root', password='password', database='taobao_shop')cursor = conn.cursor()for item in items:sql = "INSERT INTO items (num_iid, title, price, num, sold_quantity) VALUES (%s, %s, %s, %s, %s)"cursor.execute(sql, (item['num_iid'], item['title'], item['price'], item['num'], item['sold_quantity']))conn.commit()cursor.close()conn.close()
保存到Redis:
使用
redis库缓存数据,便于快速查询。
pythonimport redisr = redis.Redis(host='localhost', port=6379, db=0)for item in items:r.hset(f"item:{item['num_iid']}", "price", item['price'], "stock", item['num'], "sales", item['sold_quantity'])
状态变化检测:
定期检查商品价格、库存变化,并触发通知(邮件/短信)。
pythondef monitor_items(items, interval=60):while True:for item in items:# 重新获取商品信息updated_item = api.get_item_info(item['num_iid'])if updated_item['price'] != item['price'] or updated_item['num'] != item['num']:print(f"商品 {item['num_iid']} 状态变化: 价格 {item['price']} → {updated_item['price']}, 库存 {item['num']} → {updated_item['num']}")# 触发通知(示例:发送邮件)send_email(item['num_iid'], updated_item['price'], updated_item['num'])time.sleep(interval)
通知机制:
集成邮件或短信服务(如阿里云短信)。
pythondef send_email(item_id, price, stock):msg = f"商品 {item_id} 价格更新为 {price} 元,库存剩余 {stock} 件。"print(f"发送邮件: {msg}") # 实际代码需配置SMTP服务器matplotlib绘制销量变化趋势。
pythonimport matplotlib.pyplot as pltdef plot_sales_trend(items):dates = [item['modified_time'] for item in items] # 假设有修改时间字段sales = [int(item['sold_quantity']) for item in items]plt.plot(dates, sales)plt.xlabel('日期')plt.ylabel('销量')plt.title('商品销量趋势')plt.xticks(rotation=45)plt.tight_layout()plt.savefig('sales_trend.png')time.sleep(1)避免触发限流。40007)。通过以上步骤,您可实现一个完整的店铺商品监控系统,实时掌握商品状态变化,并扩展数据分析、通知等功能。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70046834/viewspace-3093892/ ,如需转载,请注明出处,否则将追究法律责任。