促销活动和优惠券信息的提取与计算逻辑

解读

国内主流电商(淘宝、京东、拼多多、抖音商城)的促销规则高度动态:满减、折扣券、平台券、店铺券、限时秒杀、跨店凑单、会员专享、支付立减等层层叠加,且同一商品在同一时刻可能命中多条优惠。面试官希望候选人用 Beautiful Soup 把“人读得懂、机器难解析”的网页优惠文案,转成“机器可读、可计算”的结构化数据,并给出“到手价”计算链路。核心难点有三:

  1. 优惠文本高度口语化(“每满300减40,可叠全品类券,上不封顶”),需正则+语义归一;
  2. 券门槛与商品属性(SKU、品类、店铺、会员等级)强耦合,需做“命中判定”;
  3. 优惠叠加顺序受平台策略约束(如京东先扣京豆再扣券,淘宝先扣品类券再扣店铺券),需硬编码策略表。

面试通常给一段真实的商品详情页 HTML(含优惠券弹层 JSON 埋点),要求 30 min 内写出:

  • 提取所有优惠文本 → 结构化字段;
  • 过滤出当前用户可领可用券;
  • 计算最优组合下的最低到手价;
  • 代码兼顾鲁棒性(标签缺失、字段为空、金额单位混用“元/分”)。

知识点

  1. Beautiful Soup 高级用法

    • 多选择器联合:soup.select('div[data-spm*="coupon"]') 定位券层;
    • 正则属性:soup.find_all(string=re.compile(r'满\d+减\d+'));
    • 兄弟节点与父节点回溯:优惠文本常在 <dt> 标签后,用 .next_sibling 精准取值;
    • 容错解析:bs4.UnicodeDammit 处理 GBK/压缩混用;SoupStrainer 局部解析大页面。
  2. 正则与 NLP 轻量化归一

    • 金额统一转“分”:
      re.sub(r'(\d+)元', lambda m: str(int(m.group(1))*100), txt)
    • 门槛语义标准化:
      满(\d+(?:\.\d+)?)减(\d+(?:\.\d+)?) → {"type": "full_reduction", "threshold": int, "value": int}
    • 折扣券识别:
      (\d+)折 → {"type": "discount", "rate": float(rate)/10}
  3. 优惠命中判定

    • 商品维度:SKU ID、类目 ID、店铺 ID、会员等级、渠道(APP/小程序);
    • 券维度:适用类目、排除类目、可用平台、限新/限老、限地区;
    • 判定函数:match(sku_meta, coupon_rule) -> bool,用集合快速交。
  4. 最优组合计算

    • 平台策略表(字典序优先级):
      ORDER = ['cash_back', 'full_reduction', 'discount', 'platform_coupon', 'shop_coupon']
    • 回溯+剪枝:金额相同则步长减半,复杂度 O(2^n) 实际 n≤10 可秒级;
    • 到手价公式:
      final = max(origin - Σdiscount, 0) + post_fee - red_packet
  5. 工程鲁棒

    • 金额单位异常兜底:缺单位默认“元”,超范围异常抛自定义 PriceError;
    • 空值兼容:coupon.get('threshold', 0) or 0;
    • 日志埋点:记录“文本→字段”中间态,方便后续人工复核。

答案

# -*- coding: utf-8 -*-
import re
import json
from bs4 import BeautifulSoup, SoupStrainer
from decimal import Decimal, ROUND_HALF_UP

class PriceError(Exception):
    pass

def to_cent(text: str) -> int:
    """把 3元、3.5元、350分 统一转成分,容错"""
    text = text.strip()
    if not text:
        raise PriceError('empty price')
    if '分' in text:
        return int(re.search(r'\d+', text).group())
    yuan = re.search(r'(\d+(?:\.\d+)?)', text)
    if not yuan:
        raise PriceError(f'can not parse {text}')
    return int(Decimal(yuan.group(1)) * 100)

def parse_coupon_text(txt: str):
    """把口语化文本解析成结构化规则"""
    txt = txt.replace(' ', '')
    if '满' in txt and '减' in txt:
        m = re.search(r'满(\d+(?:\.\d+)?)减(\d+(?:\.\d+)?)', txt)
        if m:
            return {
                'type': 'full_reduction',
                'threshold': to_cent(m.group(1) + '元'),
                'value': to_cent(m.group(2) + '元')
            }
    if '折' in txt:
        m = re.search(r'(\d+(?:\.\d+)?)折', txt)
        if m:
            return {
                'type': 'discount',
                'rate': float(m.group(1)) / 10
            }
    return None

def extract_coupons(html: str):
    """从商品详情页提取优惠券列表"""
    only_coupon = SoupStrainer('div', attrs={'data-spm': re.compile('coupon')})
    soup = BeautifulSoup(html, 'lxml', parse_only=only_coupon)
    coupons = []
    for block in soup.select('div.coupon-item'):
        # 优先取 JSON 埋点
        raw = block.get('data-coupon')
        if raw:
            try:
                rule = json.loads(raw)
            except:
                rule = {}
        else:
            # 降级到文本
            txt = block.get_text(strip=True)
            rule = parse_coupon_text(txt) or {}
        # 补公共字段
        rule['id'] = block.get('data-id') or rule.get('id')
        rule['quota'] = int(block.get('data-quota', 1))
        coupons.append(rule)
    return coupons

def match_coupon(sku, coupon):
    """判定券是否可叠加到当前商品"""
    if coupon.get('threshold', 0) > sku['price']:
        return False
    if coupon.get('exclude_cats') and sku['cat'] in coupon['exclude_cats']:
        return False
    return True

def best_price(origin: int, coupons, sku):
    """回溯计算最低到手价,单位分"""
    usable = [c for c in coupons if match_coupon(sku, c)]
    # 平台策略:先减后折再券
    usable.sort(key=lambda x: ('full_reduction', 'discount', 'shop_coupon', 'platform_coupon').index(x['type']))
    best = origin

    def dfs(idx, cur):
        nonlocal best
        if cur <= 0:
            best = 0
            return
        if idx == len(usable):
            best = min(best, cur)
            return
        c = usable[idx]
        if c['type'] == 'full_reduction':
            delta = c['value']
            dfs(idx+1, max(cur - delta, 0))
        elif c['type'] == 'discount':
            after = int(Decimal(cur) * Decimal(c['rate']))
            dfs(idx+1, after)
        else:
            dfs(idx+1, cur)
        # 不选这张
        dfs(idx+1, cur)

    dfs(0, origin)
    return best

# ==== 面试现场调用示例 ====
if __name__ == '__main__':
    html = open('tmall_item.htm', encoding='utf-8').read()
    coupons = extract_coupons(html)
    sku = {'price': 29900, 'cat': '50012029'}  # 299元,连衣裙类目
    final = best_price(29900, coupons, sku)
    print(f'最低到手价:{final/100:.2f}元')

拓展思考

  1. 高并发场景
    若优惠券接口需 10 ms 内返回,可把“最优组合”预计算成决策树缓存到 Redis,Key 为“商品ID+用户等级+已领券ID 有序集合”,Value 为到手价。更新策略:券池变更时异步失效。

  2. 多平台策略差异
    京东“总价促销”与“限品类东券”可叠,淘宝“品类券”与“店铺券”可叠但受“优惠分摊”算法影响,需把 best_price 抽象成策略模式,不同平台注入不同 StackingRule。

  3. 法规合规
    2020 年《规范促销行为暂行规定》要求“折抵价需真实可比”,爬虫提取的“原价”必须是近七日最低成交价,否则涉嫌价格欺诈。需在解析侧记录时间戳与快照,留痕备查。

  4. 反爬对抗
    优惠券 JSON 常被 JavaScript 加密(如淘宝的 x-encrypt),可先用 PyMiniRacer 执行局部 JS 拿到明文,再喂给 Beautiful Soup,避免完整浏览器渲染带来的性能损耗。