首页 > 大数据 > 数据分析 > 淘宝关键词搜索 API 接口详解与示例
taobao.items.searchtaobao.tbk.item.get(淘宝客 API)taobao.items.search 或
taobao.tbk.item.get 接口权限。sign 外)按字母升序排列。pythonimport hashlibimport timeimport requestsimport jsonclass TaobaoAPI:def __init__(self, app_key: str, app_secret: str):self.app_key = app_keyself.app_secret = app_secretself.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_secretreturn 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()
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_fromif price_to is not None:params["price_to"] = price_toif 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=0, **kwargs)if "error_response" in first_page:print(f"搜索失败: {first_page['error_response']['msg']}")return all_itemstotal_results = first_page.get("items_search_response", {}).get("total_results", 0)if total_results == 0:print(f"未找到匹配的商品: {keyword}")return all_itemstotal_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
pythonif __name__ == "__main__":app_key = "YOUR_APP_KEY" # 替换为实际 AppKeyapp_secret = "YOUR_APP_SECRET" # 替换为实际 AppSecretapi = TaobaoSearchAPI(app_key, app_secret)# 搜索关键词 "手机",获取前 2 页结果items = api.search_all_items("手机", max_pages=2)print(json.dumps(items, ensure_ascii=False, indent=2))
json 库解析。通过以上步骤,开发者可快速集成淘宝关键词搜索功能,适用于商品展示、比价、推荐等场景。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70046834/viewspace-3090219/ ,如需转载,请注明出处,否则将追究法律责任。