依联网作为聚焦工业零部件、自动化设备的 B2B 电商平台,其商品搜索功能(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 YilianwangSearchApi:
def __init__(self, proxy_pool: List[str] = None, cookie: str = ""):
self.base_url = "https://www.yilianwang.com/search/"
self.ua = UserAgent()
self.proxy_pool = proxy_pool # 代理池列表,如["http://ip:port", ...]
self.cookie = cookie # 登录态Cookie(用于获取完整价格)
# 分类ID映射(工业类目简化版)
self.category_map = {
"传感器": "102",
"电机": "205",
"PLC控制器": "301",
"减速机": "403"
}
# 技术参数名映射(参数显示名→接口参数名)
self.param_map = {
"额定电压": "voltage",
"防护等级": "protection",
"安装方式": "installation",
"检测距离": "distance"
}
def _get_headers(self) -> Dict[str, str]:
"""生成随机请求头"""
headers = {
"User-Agent": self.ua.random,
"Referer": "https://www.yilianwang.com/category/",
"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 _clean_moq(self, moq_str: str) -> int:
"""清洗起订量(提取数字)"""
if not moq_str:
return 1
moq_num = re.search(r"\d+", moq_str)
return int(moq_num.group()) if moq_num else 1
def _parse_param(self, param_dict: Dict[str, str]) -> str:
"""将参数字典转换为接口param格式(如{"额定电压": "24V"} → "voltage:24V")"""
param_list = []
for display_name, value in param_dict.items():
if display_name in self.param_map:
param_key = self.param_map[display_name]
param_list.append(f"{param_key}:{value}")
return ";".join(param_list)
def _parse_item(self, item_soup) -> Dict[str, str]:
"""解析单条商品数据"""
# 提取商品ID
link = item_soup.select_one("a.product-title")["href"]
item_id = re.search(r"/product/(\w+)\.html", link).group(1) if link else ""
# 提取核心参数标签(如24V、IP67)
core_params = [tag.text.strip() for tag in item_soup.select(".param-tags span")]
# 提取供应商资质
certifications = [tag.text.strip() for tag in item_soup.select(".cert-tags span")]
return {
"item_id": item_id,
"title": item_soup.select_one(".product-title")?.text.strip() or "",
"main_image": item_soup.select_one(".product-img img")?.get("src") or "",
"url": f"https://www.yilianwang.com{link}" if link.startswith("/") else link,
"price": {
"current": self._clean_price(item_soup.select_one(".price-tax")?.text or ""),
"min_order": self._clean_moq(item_soup.select_one(".moq")?.text or ""),
"batch_discount": item_soup.select_one(".batch-discount")?.text.strip() or ""
},
"core_params": core_params, # 核心技术参数标签
"supplier": {
"name": item_soup.select_one(".supplier-name")?.text.strip() or "",
"location": item_soup.select_one(".supplier-location")?.text.strip() or "",
"certifications": certifications
},
"trade": {
"stock_status": item_soup.select_one(".stock-tag")?.text.strip() or "",
"delivery_cycle": item_soup.select_one(".delivery-cycle")?.text.strip() or "",
"sales_count": int(re.search(r"\d+", item_soup.select_one(".sales-count")?.text or "0").group()) if item_soup.select_one(".sales-count") else 0
}
}
def _parse_page(self, html: str) -> List[Dict]:
"""解析页面的商品列表"""
soup = BeautifulSoup(html, "lxml")
# 商品列表容器(需根据实际页面结构调整)
item_list = soup.select("div.product-item")
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,
params: Dict[str, str] = None,
cert: List[str] = None,
stock: int = 0,
sort: str = "",
page_limit: int = 5) -> Dict:
"""
搜索依联网商品列表
:param keyword: 搜索关键词
:param category: 分类名称(如“传感器”)或分类ID
:param price_min: 最低价格(元)
:param price_max: 最高价格(元)
:param params: 技术参数字典(如{"额定电压": "24V", "防护等级": "IP67"})
:param cert: 资质列表(如["iso9001", "ce"])
:param stock: 库存状态(1=现货,0=全部)
:param sort: 排序方式(price_asc/sales等)
: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:
cat_id = self.category_map[category]
else:
cat_id = category if category else ""
# 处理技术参数
param_str = self._parse_param(params) if params else ""
# 处理资质参数
cert_str = ",".join(cert) if cert else ""
# 编码关键词
encoded_keyword = urllib.parse.quote(keyword, encoding="utf-8") if keyword else ""
all_items = []
current_page = 1
while current_page <= page_limit:
# 构建参数
params = {
"page": current_page
}
if encoded_keyword:
params["keyword"] = encoded_keyword
if cat_id:
params["cat_id"] = cat_id
if price_min is not None:
params["price_min"] = price_min
if price_max is not None:
params["price_max"] = price_max
if param_str:
params["param"] = param_str
if cert_str:
params["cert"] = cert_str
if stock in (0, 1):
params["stock"] = stock
if sort:
params["sort"] = sort
# 发送请求(带随机延迟)
time.sleep(random.uniform(4, 6)) # 工业平台延迟需更高
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和30)
total_pages = min(total_pages, page_limit, 30)
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}
if "401" in str(e):
return {"success": False, "error_msg": "需要登录,请提供有效Cookie", "code": 401}
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 = "SESSION=xxx; user_token=xxx"
# 初始化API客户端
search_api = YilianwangSearchApi(proxy_pool=PROXIES, cookie=COOKIE)
# 搜索“接近开关”,分类“传感器”,价格100-500元,技术参数24V+IP67,ISO9001认证,仅现货,按销量降序,最多3页
result = search_api.item_search(
keyword="接近开关",
category="传感器",
price_min=100,
price_max=500,
params={"额定电压": "24V", "防护等级": "IP67"},
cert=["iso9001"],
stock=1,
sort="sales",
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']['min_order']}件 | 折扣:{item['price']['batch_discount']}")
print(f"核心参数:{', '.join(item['core_params'])}")
print(f"供应商:{item['supplier']['name']}({item['supplier']['location']}) | 资质:{', '.join(item['supplier']['certifications'])}")
print(f"交易信息:{item['trade']['stock_status']} | 交货周期:{item['trade']['delivery_cycle']} | 已售:{item['trade']['sales_count']}件")
print(f"详情页:{item['url']}")
else:
print(f"搜索失败:{result['error_msg']}(错误码:{result.get('code')})")