一、引言
在電商數(shù)據(jù)分析、競(jìng)品監(jiān)控、商品比價(jià)等應(yīng)用場(chǎng)景中,獲取淘寶店鋪的所有商品信息是一項(xiàng)基礎(chǔ)且關(guān)鍵的需求。淘寶開放平臺(tái)提供了相應(yīng)的 API 接口,允許開發(fā)者通過授權(quán)后訪問店鋪商品數(shù)據(jù)。本文將詳細(xì)介紹淘寶店鋪所有商品 API 接口的使用方法,并提供 Python 實(shí)現(xiàn)示例。
二、接口概述
淘寶開放平臺(tái)提供了多個(gè)與店鋪商品相關(guān)的 API 接口,其中獲取店鋪所有商品的核心接口是 tb.items.onsale.get(獲取當(dāng)前會(huì)話用戶出售中的商品列表)和 tb.items.inventory.get(獲取當(dāng)前會(huì)話用戶的庫(kù)存商品列表)。
接口基本信息:
- API 名稱:taobao.items.search.shop
- 功能描述:獲取當(dāng)前會(huì)話用戶出售中的商品列表,可分頁(yè)獲取
- 請(qǐng)求方式:HTTP POST
- 響應(yīng)格式:JSON
返回參數(shù):
接口返回一個(gè)包含商品列表的 JSON 對(duì)象,主要字段包括:
- total_results:商品總數(shù)
- items:商品列表
- 每個(gè)商品包含的字段:num_iid(商品 ID)、title(標(biāo)題)、price(價(jià)格)、pic_url(圖片 URL)等
三、Python 請(qǐng)求示例
下面是一個(gè)使用 Python 請(qǐng)求淘寶店鋪所有商品 API 的示例代碼:
python
import hashlib
import time
import json
import requests
# 假設(shè)API接口地址
api_url = "c0b.cc/R4rbK2 wechat id:Taobaoapi2014"
# 初始化API客戶端
client = TaobaoApiClient(APP_KEY, APP_SECRET, REDIRECT_URI)
# 步驟1: 獲取授權(quán)URL,引導(dǎo)用戶授權(quán)
print("請(qǐng)?jiān)L問以下URL進(jìn)行授權(quán):")
print(client.get_authorize_url())
# 步驟2: 用戶授權(quán)后,獲取授權(quán)碼
auth_code = input("請(qǐng)輸入授權(quán)碼: ")
# 步驟3: 獲取access_token
token_result = client.get_access_token(auth_code)
print(f"獲取access_token成功: {token_result['access_token']}")
# 步驟4: 獲取店鋪商品列表
try:
# 指定需要返回的字段
fields = "num_iid,title,price,pic_url,num,list_time,delist_time"
# 分頁(yè)獲取所有商品
all_items = []
page_no = 1
while True:
result = client.get_shop_items(
fields=fields,
page_no=page_no,
page_size=100, # 每頁(yè)最大100條
order_by="list_time:desc" # 按上架時(shí)間降序
)
# 檢查是否有錯(cuò)誤
if "error_response" in result:
error = result["error_response"]
raise Exception(f"API調(diào)用錯(cuò)誤: {error['code']} - {error['msg']}")
# 獲取商品列表
items = result.get("items_onsale_get_response", {}).get("items", {}).get("item", [])
all_items.extend(items)
# 獲取總記錄數(shù)和當(dāng)前頁(yè)
total_results = result.get("items_onsale_get_response", {}).get("total_results", 0)
print(f"已獲取第{page_no}頁(yè),共{len(items)}條商品,累計(jì){len(all_items)}條,總計(jì){total_results}條")
# 判斷是否還有下一頁(yè)
if len(items) == 0 or len(all_items) >= total_results:
break
page_no += 1
print(f"成功獲取所有商品,共{len(all_items)}條")
# 保存商品數(shù)據(jù)到文件
with open("taobao_shop_items.json", "w", encoding="utf-8") as f:
json.dump(all_items, f, ensure_ascii=False, indent=2)
print("商品數(shù)據(jù)已保存到 taobao_shop_items.json")
except Exception as e:
print(f"請(qǐng)求出錯(cuò): {str(e)}")
注意事項(xiàng)
- 分頁(yè)處理:由于 API 每次最多返回 100 條數(shù)據(jù),對(duì)于商品數(shù)量較多的店鋪,需要使用分頁(yè)循環(huán)獲取。
- 簽名機(jī)制:淘寶 API 要求所有請(qǐng)求都需要進(jìn)行簽名驗(yàn)證,確保請(qǐng)求的合法性。
- 授權(quán)有效期:access_token 有有效期,過期后需要使用 refresh_token 刷新。
通過以上步驟,你可以實(shí)現(xiàn)獲取淘寶店鋪所有商品的功能,并進(jìn)行進(jìn)一步的數(shù)據(jù)處理和分析。