一、核心 API 接口选择
1.1 推荐接口:taobao.items.search
- 功能:通过关键词搜索淘宝商品,支持分页、筛选和排序。
- 权限等级:需申请并通过审核。
- 返回数据:商品列表(含标题、价格、图片、销量等)。
1.2 备选接口:taobao.tbk.item.get
(淘宝客 API)
- 功能:获取淘宝客推广商品(含佣金信息)。
- 适用场景:用于推广返利类应用。
- 限制:需绑定淘宝客账号。
二、开发准备
2.1 申请应用与权限
- 注册淘宝开放平台账号:访问淘宝开放平台 完成注册及实名认证。
- 创建应用:在控制台创建应用,选择类型为“自用型”或“他用型”。
- 申请接口权限:在应用详情页中,申请
taobao.items.search
或taobao.tbk.item.get
接口权限。
2.2 获取 AppKey 和 AppSecret
- 在应用详情页中获取 AppKey 和 AppSecret,这是调用 API 的必要凭证。
2.3 签名机制
- 签名生成步骤:
三、完整代码示例(Python)
3.1 基础 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} 个商品,共 {total_pages} 页") for page in range(1, total_pages + 1): print(f"正在获取第 {page}/{total_pages} 页...") 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)} 个商品") return all_items
3.3 使用示例
pythonif __name__ == "__main__": app_key = "YOUR_APP_KEY" # 替换为实际 AppKey app_secret = "YOUR_APP_SECRET" # 替换为实际 AppSecret api = TaobaoSearchAPI(app_key, app_secret) # 搜索关键词 "手机",获取前 2 页结果 items = api.search_all_items("手机", max_pages=2) print(json.dumps(items, ensure_ascii=False, indent=2))
四、注意事项
- 权限申请:调用前需确保已申请对应接口权限。
- 签名验证:签名错误会导致调用失败,请严格按规则生成。
- 频率限制:遵守淘宝开放平台的调用频率限制,避免封号。
- 数据解析:返回数据为 JSON 格式,需使用
json
库解析。
通过以上步骤,开发者可快速集成淘宝关键词搜索功能,适用于商品展示、比价、推荐等场景。