慧聪网作为国内领先的 B2B 电商平台,聚焦工业品、原材料等批发采购场景,其商品详情数据(如价格、规格、供应商信息、起订量等)是 B2B 比价工具、供应商监控系统、行业数据分析平台的核心数据源。由于慧聪网无公开官方 API,开发者需通过合规的页面解析或第三方服务实现商品详情(item_get)的获取。本文将系统讲解接口对接逻辑、技术实现、反爬应对及最佳实践,帮助开发者构建稳定的商品详情获取系统。
一、接口基础认知(核心功能与场景)
二、对接前置准备(环境与工具)
三、接口调用流程(基于页面解析)
四、代码实现示例(Python)
import requests
import time
import random
import re
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from typing import Dict, List
class HuicongItemApi:
def __init__(self, proxy_pool: List[str] = None):
self.base_url = "https://www.hc360.com/supplyself/{item_id}.html"
self.price_api = "https://www.hc360.com/ajax/getPriceInfo?itemId={item_id}" # 价格梯度接口
self.ua = UserAgent()
self.proxy_pool = proxy_pool # 代理池列表,如["http://ip:port", ...]
def _get_headers(self) -> Dict[str, str]:
"""生成随机请求头"""
return {
"User-Agent": self.ua.random,
"Referer": "https://www.hc360.com/",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Cookie": "uuid=anonymous; userid=xxx; _hc360_cookie_id=xxx" # 替换为实际Cookie
}
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 _parse_static_data(self, html: str) -> Dict[str, str]:
"""解析静态HTML中的基础信息"""
soup = BeautifulSoup(html, "lxml")
return {
"title": soup.select_one("h1.title")?.text.strip() or "",
"supplier_name": soup.select_one("a.supplier-name")?.text.strip() or "",
"location": soup.select_one("div.location")?.text.strip() or "",
"business_mode": soup.select_one("div.business-mode")?.text.strip() or "",
"images": [img.get("src") for img in soup.select("div.img-list img") if img.get("src")],
"detail_html": str(soup.select_one("div.detail-content") or "") # 商品详情HTML
}
def _fetch_dynamic_data(self, item_id: str, headers: Dict[str, str], proxy: Dict[str, str]) -> Dict:
"""调用动态接口获取价格梯度与库存"""
try:
url = self.price_api.format(item_id=item_id)
response = requests.get(url, headers=headers, proxies=proxy, timeout=10)
response.raise_for_status()
return response.json()
except Exception as e:
print(f"动态接口获取失败: {str(e)}")
return {}
def _parse_dynamic_data(self, dynamic_data: Dict) -> Dict:
"""解析动态数据(价格梯度、起订量、库存)"""
price_list = dynamic_data.get("priceList", [])
# 格式化价格梯度(如[{min:100, max:499, price:80}, ...])
formatted_prices = []
for i, price in enumerate(price_list):
min_qty = price.get("quantity")
max_qty = price_list[i+1].get("quantity") - 1 if i+1 < len(price_list) else "∞"
formatted_prices.append({
"min_quantity": min_qty,
"max_quantity": max_qty,
"price": price.get("price")
})
return {
"price": {
"market": dynamic_data.get("marketPrice", 0),
"wholesale": formatted_prices,
"min_order": dynamic_data.get("minOrder", 0)
},
"stock": dynamic_data.get("stock", 0)
}
def item_get(self, item_id: str, timeout: int = 10) -> Dict:
"""
获取慧聪网商品详情
:param item_id: 商品ID(如267890123)
:param timeout: 超时时间
:return: 标准化商品数据
"""
try:
# 1. 构建URL并发送请求
url = self.base_url.format(item_id=item_id)
headers = self._get_headers()
proxy = self._get_proxy()
# 随机延迟,避免反爬
time.sleep(random.uniform(2, 4))
response = requests.get(
url=url,
headers=headers,
proxies=proxy,
timeout=timeout
)
response.raise_for_status()
html = response.text
# 2. 解析静态数据
static_data = self._parse_static_data(html)
if not static_data["title"]:
return {"success": False, "error_msg": "未找到商品信息,可能item_id错误或商品已下架"}
# 3. 获取并解析动态数据
dynamic_data = self._fetch_dynamic_data(item_id, headers, proxy)
dynamic_parsed = self._parse_dynamic_data(dynamic_data)
# 4. 合并数据
result = {
"success": True,
"data": {
"item_id": item_id,
**static_data,** dynamic_parsed,
"update_time": time.strftime("%Y-%m-%d %H:%M:%S")
}
}
return result
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"
]
# 初始化API客户端
api = HuicongItemApi(proxy_pool=PROXIES)
# 获取商品详情(示例item_id)
item_id = "267890123" # 替换为实际商品ID
result = api.item_get(item_id)
if result["success"]:
data = result["data"]
print(f"商品标题: {data['title']}")
print(f"供应商: {data['supplier_name']} | 所在地: {data['location']} | 经营模式: {data['business_mode']}")
print(f"市场价: {data['price']['market']}元 | 起订量: {data['price']['min_order']}件")
print("价格梯度:")
for grad in data['price']['wholesale']:
print(f" {grad['min_quantity']}-{grad['max_quantity']}件: {grad['price']}元/件")
print(f"库存: {data['stock']}件 | 主图数量: {len(data['images'])}张")
else:
print(f"获取失败: {result['error_msg']}(错误码: {result.get('code')})")