一、核心 API 接口選擇
1.1 推薦接口:taobao.items.search
- 功能:通過(guò)關(guān)鍵詞搜索淘寶商品,支持分頁(yè)、篩選和排序。
- 權(quán)限等級(jí):需申請(qǐng)并通過(guò)審核。
- 返回?cái)?shù)據(jù):商品列表(含標(biāo)題、價(jià)格、圖片、銷量等)。
1.2 備選接口:taobao.tbk.item.get
(淘寶客 API)
- 功能:獲取淘寶客推廣商品(含傭金信息)。
- 適用場(chǎng)景:用于推廣返利類應(yīng)用。
- 限制:需綁定淘寶客賬號(hào)。
二、開(kāi)發(fā)準(zhǔn)備
2.1 申請(qǐng)應(yīng)用與權(quán)限
- 注冊(cè)淘寶開(kāi)放平臺(tái)賬號(hào):訪問(wèn)淘寶開(kāi)放平臺(tái) 完成注冊(cè)及實(shí)名認(rèn)證。
- 創(chuàng)建應(yīng)用:在控制臺(tái)創(chuàng)建應(yīng)用,選擇類型為“自用型”或“他用型”。
- 申請(qǐng)接口權(quán)限:在應(yīng)用詳情頁(yè)中,申請(qǐng)
taobao.items.search
或taobao.tbk.item.get
接口權(quán)限。
2.2 獲取 AppKey 和 AppSecret
- 在應(yīng)用詳情頁(yè)中獲取 AppKey 和 AppSecret,這是調(diào)用 API 的必要憑證。
2.3 簽名機(jī)制
- 簽名生成步驟:
三、完整代碼示例(Python)
3.1 基礎(chǔ) API 客戶端
pythonimport hashlibimport timeimport requestsimport json class TaobaoAPI: def __init__(self, app_key: str, app_secret: str): self.app_key = app_key self.app_secret = app_secret self.api_url = "https://eco.taobao.com/router/rest" def generate_sign(self, params: dict) -> str: 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 if k != 'sign']) + self.app_secret return hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper() def call(self, method: str, params: dict) -> dict: 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()
3.2 商品搜索 API
pythonclass TaobaoSearchAPI(TaobaoAPI): def search_items(self, keyword: str, page_no: int = 1, page_size: int = 40, sort: str = "default", price_from: float = None, price_to: float = None, has_discount: bool = False, is_tmall: bool = False) -> dict: params = { "q": keyword, "page_no": page_no, "page_size": page_size, "sort": sort, "fields": "num_iid,title,nick,pic_url,price,original_price,detail_url,sell_count" } if price_from is not None: params["price_from"] = price_from if price_to is not None: params["price_to"] = price_to if has_discount: params["has_discount"] = "true" if is_tmall: params["is_tmall"] = "true" return self.call("taobao.items.search", params) def search_all_items(self, keyword: str, max_pages: int = 10, **kwargs) -> list: all_items = [] first_page = self.search_items(keyword, page_no=1, **kwargs) if "error_response" in first_page: print(f"搜索失敗: {first_page['error_response']['msg']}") return all_items total_results = first_page.get("items_search_response", {}).get("total_results", 0) if total_results == 0: print(f"未找到匹配的商品: {keyword}") return all_items total_pages = min(math.ceil(total_results / kwargs.get("page_size", 40)), max_pages) print(f"找到 {total_results} 個(gè)商品,共 {total_pages} 頁(yè)") for page in range(1, total_pages + 1): print(f"正在獲取第 {page}/{total_pages} 頁(yè)...") result = self.search_items(keyword, page_no=page, **kwargs) items = result.get("items_search_response", {}).get("items", {}).get("item", []) all_items.extend(items) time.sleep(1) print(f"成功獲取 {len(all_items)} 個(gè)商品") return all_items
3.3 使用示例
pythonif __name__ == "__main__": app_key = "YOUR_APP_KEY" # 替換為實(shí)際 AppKey app_secret = "YOUR_APP_SECRET" # 替換為實(shí)際 AppSecret api = TaobaoSearchAPI(app_key, app_secret) # 搜索關(guān)鍵詞 "手機(jī)",獲取前 2 頁(yè)結(jié)果 items = api.search_all_items("手機(jī)", max_pages=2) print(json.dumps(items, ensure_ascii=False, indent=2))
四、注意事項(xiàng)
- 權(quán)限申請(qǐng):調(diào)用前需確保已申請(qǐng)對(duì)應(yīng)接口權(quán)限。
- 簽名驗(yàn)證:簽名錯(cuò)誤會(huì)導(dǎo)致調(diào)用失敗,請(qǐng)嚴(yán)格按規(guī)則生成。
- 頻率限制:遵守淘寶開(kāi)放平臺(tái)的調(diào)用頻率限制,避免封號(hào)。
- 數(shù)據(jù)解析:返回?cái)?shù)據(jù)為 JSON 格式,需使用
json
庫(kù)解析。
通過(guò)以上步驟,開(kāi)發(fā)者可快速集成淘寶關(guān)鍵詞搜索功能,適用于商品展示、比價(jià)、推薦等場(chǎng)景。