ITPub博客

首页 > 大数据 > 数据分析 > 淘宝关键词搜索 API 接口详解与示例

淘宝关键词搜索 API 接口详解与示例

原创 数据分析 作者:OneLafite 时间:2025-07-07 10:38:33 0 删除 编辑

一、核心 API 接口选择

1.1 推荐接口: taobao.items.search

  • 功能:通过关键词搜索淘宝商品,支持分页、筛选和排序。
  • 权限等级:需申请并通过审核。
  • 返回数据:商品列表(含标题、价格、图片、销量等)。

1.2 备选接口: taobao.tbk.item.get(淘宝客 API)

  • 功能:获取淘宝客推广商品(含佣金信息)。
  • 适用场景:用于推广返利类应用。
  • 限制:需绑定淘宝客账号。

二、开发准备

2.1 申请应用与权限

  1. 注册淘宝开放平台账号:访问某宝开放平台 完成注册及实名认证。
  2. 创建应用:在控制台创建应用,选择类型为“自用型”或“他用型”。
  3. 申请接口权限:在应用详情页中,申请  taobao.items.search 或  taobao.tbk.item.get 接口权限。

2.2 获取 AppKey 和 AppSecret

  • 在应用详情页中获取  AppKey 和  AppSecret,这是调用 API 的必要凭证。

2.3 签名机制

  • 签名生成步骤:
    1. 将所有请求参数(除  sign 外)按字母升序排列。
    2. 拼接参数名和参数值(不包含特殊符号)。
    3. 在首尾各追加 AppSecret。
    4. 对拼接字符串进行 MD5 加密并转为大写。

三、完整代码示例(Python)

3.1 基础 API 客户端

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

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_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

3.3 使用示例

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

四、注意事项

  1. 权限申请:调用前需确保已申请对应接口权限。
  2. 签名验证:签名错误会导致调用失败,请严格按规则生成。
  3. 频率限制:遵守淘宝开放平台的调用频率限制,避免封号。
  4. 数据解析:返回数据为 JSON 格式,需使用  json 库解析。

通过以上步骤,开发者可快速集成淘宝关键词搜索功能,适用于商品展示、比价、推荐等场景。


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

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

注册时间:2025-06-20

  • 博文量
    231
  • 访问量
    258525