ITPub博客

首页 > 大数据 > 数据分析 > 如何将淘宝获取店铺所有商品API接口应用到自己店铺?实战讲解详细步骤

如何将淘宝获取店铺所有商品API接口应用到自己店铺?实战讲解详细步骤

原创 数据分析 作者:OneLafite 时间:2025-08-20 17:41:50 0 删除 编辑

一、前期准备

1.  注册开发者账号并创建应用

  • 注册淘宝开放平台账号:
    访问淘宝开放平台,使用淘宝账号登录并完成实名认证(个人需绑定支付宝,企业需提交营业执照)。
  • 创建应用:
    进入控制台 > 应用管理 > 创建应用,填写应用名称、类型(自用型/他用型)及场景描述。
    • 应用类型选择:
      • 自用型:适用于仅管理自己店铺的场景,权限申请较简单。
      • 他用型:适用于为其他商家提供服务的场景,需额外审核。
  • 获取App Key和App Secret:
    应用创建后,在应用详情页获取 App Key和 App Secret(调用API的凭证)。

2.  申请API权限

  • 申请 taobao.items.onsale.get接口权限:
    该接口用于获取店铺在售商品列表,是核心接口。
    • 路径:控制台 > 应用管理 > 权限管理 > 申请权限。
    • 权限说明:
      • 基础权限:可直接申请,用于获取商品基础信息(如ID、标题、价格)。
      • 高级权限:需提交应用场景审核(如商品管理、数据分析),可获取销量、库存等详细字段。
  • 其他推荐权限:
    • taobao.item.get:获取单个商品详情(如库存、SKU)。
    • taobao.shop.get:获取店铺基本信息(如店铺ID)。

3.  环境配置

  • 安装Python依赖库:
    bashpip install requests hashlib pandas
  • 准备工具:
    • 文本编辑器(如VS Code)或Jupyter Notebook。
    • 数据库(可选,如MySQL、Redis)用于存储商品数据。

二、核心代码实现

1.  API调用基础类

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()

2.  获取店铺在售商品列表

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

3.  示例调用与结果处理

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}")

三、进阶功能扩展

1.  数据存储与持久化

  • 保存到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'])

2.  实时监控与通知

  • 状态变化检测:
    定期检查商品价格、库存变化,并触发通知(邮件/短信)。

    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服务器

3.  数据分析与可视化

  • 生成销量趋势图:
    使用 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')

四、注意事项

  1. 频率限制:
    • 淘宝API对调用次数有限制(基础权限每日1000次),建议合理设置检查间隔(如1-5分钟)。
    • 分页请求时添加 time.sleep(1)避免触发限流。
  2. 数据准确性:
    • 部分数据(如库存)可能存在延迟,建议结合订单状态综合判断。
    • 定期校验数据,确保与店铺后台一致。
  3. 合规性:
    • 禁止爬取用户隐私数据,确保数据使用符合淘宝开放平台API文档页面。
    • 敏感信息(如App Secret)需加密存储,避免泄露。
  4. 错误处理:
    • 添加重试机制(如3次重试)应对网络超时或签名错误(错误码 40007)。
    • 记录错误日志,便于排查问题。

通过以上步骤,您可实现一个完整的店铺商品监控系统,实时掌握商品状态变化,并扩展数据分析、通知等功能。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70046834/viewspace-3093892/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
专业研发电商平台API开放接口,搭建独立站系统,反向海淘代购系统十年+,https://o0b.cn/lafite。

注册时间:2025-06-20

  • 博文量
    231
  • 访问量
    258444