供应链信息的提取:发货地、物流时效、供应商信息
解读
国内电商页面(淘宝、京东、拼多多、1688)的供应链字段通常散落在三个区域:
- 主图下方“发货地”标签(<span class="delivery-place">浙江 杭州</span>);
- 商品参数表(<ul class="parameter">里<dt>发货地</dt><dd>广东 深圳</dd>);
- 店铺档案页(异步接口返回 JSON,渲染后插入 DOM)。
物流时效往往用“24h 发货”“48h 发货”“当日发”等文案,或直接给出“预计 3 月 21 日送达”;供应商信息则藏在“公司档案”“工商执照”弹层里,需要二次请求。
面试时,面试官想确认三件事:
- 你能否在“半结构甚至烂结构”的 HTML 里精准定位;
- 你能否用 BS4 的 API 组合(find/find_all/CSS 选择器/正则)处理“字段名与字段值分离”的国内模板;
- 你能否把“可能缺失”“同义多词”“需要单位换算”的脏数据清洗成标准 JSON。
知识点
- BS4 解析流程:requests → resp.content.decode('gbk', 'ignore') → BeautifulSoup(html, 'lxml'),国内站点仍大量 GBK。
- 多策略定位:
- 发货地:先抓
<span class=".*place.*">;缺失时遍历兄弟节点“发货地:浙江 杭州”做正则 split。 - 物流时效:用
re.compile(r'(\d{1,2})[h小时]|当日发|次日达')提取数字,统一换算成“小时”。 - 供应商:店铺名在
<a class="shop-name">,营业执照在弹层 iframe,需拿data-url再发一次请求,用 BS4 解析返回的 JSONP 中的“companyName”“location”。
- 发货地:先抓
- 容错与回退:
- 标签残缺时,用
soup.select_one('body').get_text()再正则兜底; - 字段缺失写 None,不抛异常;
- 地域字段用
zhconv.convert(to='cn')把“廣東”转“广东”。
- 标签残缺时,用
- 性能与礼貌:
- 解析部分<100 ms,不打开浏览器;
- 加
time.sleep(random.uniform(0.5,1.5))及headers={'Referer': ...},避免被 1688 反爬 302 跳转。
- 输出规范:
{ "ship_from": {"province":"广东","city":"深圳"}, "shipping_time": {"value":24,"unit":"hour"}, "supplier": {"name":"深圳市××科技有限公司","location":"广东 深圳"} }
答案
import requests, re, json, random, zhconv
from bs4 import BeautifulSoup
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Referer': 'https://detail.1688.com/'
}
def fetch(url):
r = requests.get(url, headers=HEADERS, timeout=8)
r.encoding = r.apparent_encoding # 自动识别 gbk / utf-8
return r.text
def extract_supply_chain(url: str) -> dict:
html = fetch(url)
soup = BeautifulSoup(html, 'lxml')
# 1. 发货地
place = None
tag = soup.select_one('span.delivery-place, span.send-area, [data-spm="deliveryPlace"]')
if tag:
place = tag.get_text(strip=True)
else:
# 兜底:正则匹配“发货地:浙江 杭州”
m = re.search(r'发货地[::]\s*([^\s]+)\s*([^\s]+)', soup.text)
if m:
place = f"{m.group(1)} {m.group(2)}"
# 清洗
if place:
place = zhconv.convert(place, 'zh-cn')
province, city = place.split() if ' ' in place else (place, '')
else:
province, city = '', ''
# 2. 物流时效
shipping_time = None
txt = soup.get_text()
m = re.search(r'(\d{1,2})\s*[h小时]|当日发', txt)
if m:
shipping_time = int(m.group(1)) if m.group(1) else 0
else:
m = re.search(r'(\d{1,2}).*?[天日内].*?送达', txt)
if m:
shipping_time = int(m.group(1)) * 24
shipping_time = shipping_time or None
# 3. 供应商
supplier_name, supplier_loc = None, None
shop_tag = soup.select_one('a.shop-name, .company-name, [data-spm="shopName"]')
if shop_tag:
supplier_name = shop_tag.get_text(strip=True)
# 尝试抓营业执照弹层
iframe = soup.select_one('iframe[src*="company"]')
if iframe:
iframe_url = iframe['src']
if not iframe_url.startswith('http'):
iframe_url = 'https:' + iframe_url
try:
iframe_html = fetch(iframe_url)
iframe_soup = BeautifulSoup(iframe_html, 'lxml')
# 1688 返回的是 JSONP,可直接正则
m = re.search(r'"companyName":"([^"]+)"', iframe_html)
if m:
supplier_name = m.group(1)
m = re.search(r'"location":"([^"]+)"', iframe_html)
if m:
supplier_loc = m.group(1)
except Exception:
pass
return {
"ship_from": {"province": province, "city": city},
"shipping_time": {"value": shipping_time, "unit": "hour"} if shipping_time else None,
"supplier": {"name": supplier_name, "location": supplier_loc or f"{province} {city}".strip()}
}
# 调用示例
if __name__ == '__main__':
url_demo = 'https://detail.1688.com/offer/123456789.html'
print(json.dumps(extract_supply_chain(url_demo), ensure_ascii=False, indent=2))
拓展思考
- 反爬升级:1688 把关键字段放到
window.__INIT_DATA__的 JSON 里,再用 JS 加密。此时 BS4 只能拿到骨架,需要先用execjs或mitmproxy把 JSON 捞出来,再用 BS4 解析,体现“BS4+JS 解密”混合链路的思路。 - 多源交叉验证:发货地可能在“商品参数”“店铺档案”“物流详情页”三处出现,值不一致时,按“物流详情 > 商品参数 > 店铺档案”优先级仲裁,展示你对业务置信度的理解。
- 时效粒度细化:除“小时”外,部分天猫超市商品给出“今天 15:00 前付款,预计今天 22:00 送达”,需要把“日期+时间”解析成 datetime 对象,再与当前时间差值,输出“剩余分钟数”,考验正则与 datetime 运算。
- 通用模板沉淀:把“字段名→选择器/正则”做成 YAML 配置,如
place: ['css:span.delivery-place', 'regex:发货地[::]\s*([^\s]+)\s*([^\s]+)'],实现“零代码”适配新站点,体现可扩展架构思维。