什么值得买(SMZDM)作为国内领先的消费决策平台,以 “优惠信息、真实评测、社区讨论” 为核心竞争力,其商品搜索功能(item_search接口,非官方命名)是获取消费导向型商品列表的关键入口。数据包含历史低价、用户评分、优惠标签等决策属性,对电商比价、消费趋势分析、优惠监控等场景具有重要价值。由于平台无公开官方 API,开发者需通过页面解析实现搜索对接。本文系统讲解接口逻辑、参数解析、技术实现及反爬策略,助你构建稳定的消费决策类商品列表获取系统。
一、接口基础认知(核心功能与场景)
二、对接前置准备(参数与 URL 结构)
三、接口调用流程(基于页面解析)
四、代码实现示例(Python)
import requests
import time
import random
import re
import urllib.parse
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from typing import List, Dict
class SmzdmSearchApi:
def __init__(self, proxy_pool: List[str] = None, cookie: str = ""):
self.base_url = "https://www.smzdm.com/search/"
self.ua = UserAgent()
self.proxy_pool = proxy_pool # 代理池列表,如["http://ip:port", ...]
self.cookie = cookie # 登录态Cookie(用于获取完整优惠信息)
# 分类ID映射(简化版)
self.category_map = {
"耳机音箱": "157",
"家用电器": "74",
"母婴用品": "118",
"美妆个护": "145"
}
# 平台编码映射(简化版)
self.mall_map = {
"京东": "jd",
"天猫": "tmall",
"淘宝": "taobao",
"拼多多": "pinduoduo"
}
def _get_headers(self) -> Dict[str, str]:
"""生成随机请求头"""
headers = {
"User-Agent": self.ua.random,
"Referer": "https://www.smzdm.com/",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
if self.cookie:
headers["Cookie"] = self.cookie
return headers
def _get_proxy(self) -> Dict[str, str]:
"""随机获取代理"""
if self.proxy_pool and len(self.proxy_pool) > 0:
proxy = random.choice(self.proxy_pool)
return {"http": proxy, "https": proxy}
return None
def _clean_price(self, price_str: str) -> float:
"""清洗价格字符串(去除¥、文字等)"""
if not price_str:
return 0.0
price_str = re.sub(r"[^\d.]", "", price_str)
return float(price_str) if price_str else 0.0
def _parse_history_lowest(self, history_str: str) -> Dict[str, str]:
"""解析历史低价(如“历史最低¥799(2023-11)”)"""
if not history_str:
return {"price": 0.0, "date": ""}
price_match = re.search(r"¥(\d+\.?\d*)", history_str)
date_match = re.search(r"\((\d{4}-\d{2})\)", history_str)
return {
"price": self._clean_price(price_match.group(1)) if price_match else 0.0,
"date": date_match.group(1) if date_match else ""
}
def _parse_item(self, item_soup) -> Dict[str, str]:
"""解析单条商品数据"""
# 提取商品ID
link = item_soup.select_one("a.feed-title")["href"]
item_id = re.search(r"/p/(\d+)/", link).group(1) if link else ""
# 提取优惠标签(可能多个)
tags = [tag.text.strip() for tag in item_soup.select(".tag")]
return {
"item_id": item_id,
"title": item_soup.select_one(".feed-title")?.text.strip() or "",
"main_image": item_soup.select_one(".feed-img img")?.get("src") or "",
"url": f"https://www.smzdm.com{link}" if link.startswith("/") else link,
"price": {
"current": self._clean_price(item_soup.select_one(".z-price")?.text or ""),
"history_lowest": self._parse_history_lowest(item_soup.select_one(".history-lowest")?.text or "")
},
"user_feedback": {
"rating": float(item_soup.select_one(".rating")?.text or "0"),
"comment_count": int(re.search(r"\d+", item_soup.select_one(".comment-count")?.text or "0").group()) if item_soup.select_one(".comment-count") else 0
},
"platform": {
"source": item_soup.select_one(".mall-label")?.text.strip() or "",
"buy_url": item_soup.select_one(".buy-link")?.get("href") or ""
},
"tags": tags, # 优惠标签(如“满减”“百亿补贴”)
"post_time": item_soup.select_one(".time")?.text.strip() or "" # 爆料时间
}
def _parse_page(self, html: str) -> List[Dict]:
"""解析页面的商品列表"""
soup = BeautifulSoup(html, "lxml")
# 商品列表容器(需根据实际页面结构调整)
item_list = soup.select("li.feed-row")
return [self._parse_item(item) for item in item_list if item]
def _get_total_pages(self, html: str) -> int:
"""获取总页数"""
soup = BeautifulSoup(html, "lxml")
page_box = soup.select_one(".pagination")
if not page_box:
return 1
# 提取最后一页页码
last_page = page_box.select("a")[-1].text.strip()
return int(last_page) if last_page.isdigit() else 1
def item_search(self,
keyword: str = "",
category: str = "",
price_min: float = None,
price_max: float = None,
mall: str = "",
coupon: int = 0,
sort: str = "",
page_limit: int = 5) -> Dict:
"""
搜索值得买商品列表
:param keyword: 搜索关键词
:param category: 分类名称(如“耳机音箱”)或分类ID
:param price_min: 最低价格(元)
:param price_max: 最高价格(元)
:param mall: 来源平台名称(如“京东”)或编码(如“jd”)
:param coupon: 是否含优惠券(1=是,0=否)
:param sort: 排序方式(price/rating等)
:param page_limit: 最大页数(默认5)
:return: 标准化搜索结果
"""
try:
# 1. 参数预处理
if not keyword and not category:
return {"success": False, "error_msg": "关键词(keyword)和分类(category)至少需提供一个"}
# 转换分类名称为ID
if category in self.category_map:
cid = self.category_map[category]
else:
cid = category if category else ""
# 转换平台名称为编码
if mall in self.mall_map:
mall_code = self.mall_map[mall]
else:
mall_code = mall if mall else ""
# 编码关键词
encoded_keyword = urllib.parse.quote(keyword, encoding="utf-8") if keyword else ""
all_items = []
current_page = 1
while current_page <= page_limit:
# 构建参数
params = {
"p": current_page
}
if encoded_keyword:
params["s"] = encoded_keyword
if cid:
params["c"] = cid
if price_min is not None:
params["price_min"] = price_min
if price_max is not None:
params["price_max"] = price_max
if mall_code:
params["mall"] = mall_code
if coupon in (0, 1):
params["coupon"] = coupon
if sort:
params["v"] = sort
# 发送请求(带随机延迟)
time.sleep(random.uniform(2, 3)) # 控制频率,避免反爬
headers = self._get_headers()
proxy = self._get_proxy()
response = requests.get(
url=self.base_url,
params=params,
headers=headers,
proxies=proxy,
timeout=10
)
response.raise_for_status()
html = response.text
# 解析当前页商品
items = self._parse_page(html)
if not items:
break # 无数据,终止分页
all_items.extend(items)
# 获取总页数(仅第一页需要)
if current_page == 1:
total_pages = self._get_total_pages(html)
# 修正最大页数(不超过page_limit和20)
total_pages = min(total_pages, page_limit, 20)
if total_pages < current_page:
break
# 若当前页是最后一页,终止
if current_page >= total_pages:
break
current_page += 1
# 去重(基于item_id)
seen_ids = set()
unique_items = []
for item in all_items:
if item["item_id"] not in seen_ids:
seen_ids.add(item["item_id"])
unique_items.append(item)
return {
"success": True,
"total": len(unique_items),
"page_processed": current_page,
"items": unique_items
}
except requests.exceptions.HTTPError as e:
if "403" in str(e):
return {"success": False, "error_msg": "触发反爬,建议更换代理或Cookie", "code": 403}
return {"success": False, "error_msg": f"HTTP错误: {str(e)}", "code": response.status_code}
except Exception as e:
return {"success": False, "error_msg": f"搜索失败: {str(e)}", "code": -1}
# 使用示例
if __name__ == "__main__":
# 代理池(替换为有效代理)
PROXIES = [
"http://123.45.67.89:8888",
"http://98.76.54.32:8080"
]
# 登录态Cookie(从浏览器获取,用于完整优惠信息)
COOKIE = "sess=xxx; user_id=xxx; device_id=xxx"
# 初始化API客户端
search_api = SmzdmSearchApi(proxy_pool=PROXIES, cookie=COOKIE)
# 搜索“无线耳机”,分类“耳机音箱”,价格500-1000元,来源京东,含优惠券,按历史低价排序,最多3页
result = search_api.item_search(
keyword="无线耳机",
category="耳机音箱",
price_min=500,
price_max=1000,
mall="京东",
coupon=1,
sort="price",
page_limit=3
)
if result["success"]:
print(f"搜索成功:共找到 {result['total']} 件商品,处理 {result['page_processed']} 页")
for i, item in enumerate(result["items"][:5]): # 打印前5条
print(f"\n商品 {i+1}:")
print(f"标题:{item['title'][:50]}...") # 截断长标题
print(f"价格:当前¥{item['price']['current']} | 历史最低¥{item['price']['history_lowest']['price']}({item['price']['history_lowest']['date']})")
print(f"用户评分:{item['user_feedback']['rating']}分 | 评价数:{item['user_feedback']['comment_count']}条")
print(f"来源平台:{item['platform']['source']} | 优惠标签:{', '.join(item['tags'])}")
print(f"爆料时间:{item['post_time']} | 详情页:{item['url']}")
else:
print(f"搜索失败:{result['error_msg']}(错误码:{result.get('code')})")