面对动态字体映射反爬,如何基于 OCR 与字体文件重建映射表,给出 Python 伪代码
解读
-
场景还原
国内电商、点评、房产等平台普遍采用「动态字体 + 随机类名」反爬:- 每次请求返回的 woff/ttf 字体中,字形轮廓不变,但 Unicode→glyph 的映射随机打乱;
- 页面 CSS 通过
@font-face把自定义字体打到本地,前端用伪 Unicode(如\uE234)显示“3”; - 服务端同步把真实数字藏在接口或图片里,爬虫若直接取 HTML 会拿到乱码。
-
面试考点
- 能否把“字形”作为唯一指纹,绕过 Unicode 的随机性;
- 能否把「字体解析 → 字形矢量化 → 识别 → 映射表」做成全自动闭环;
- 工程化细节:缓存、并发、降噪、版本漂移、版权合规。
-
答题策略
先讲思路,再给可运行伪代码,最后补充鲁棒性方案;全程体现“数据采集工程师”的复合能力:协议解析、图像处理、分布式缓存、合规意识。
知识点
- SFNT 字体结构(head、glyf、loca、 cmap)
- 字形哈希:轮廓点序列 → 归一化 → 向量哈希(如 perceptual hash、AHash、DHash)
- OCR 备选:Tesseract、EasyOCR、PaddleOCR,以及“自训练 CNN+CTC”解决数字/小数点/千分位
- 缓存层:Redis Hash「字形hash → 真实字符」+ 本地 LRU,防止重复识别
- 合规:只采集“公开访问页面”,不破解加密接口;字体文件仅用于“可读性还原”,不二次分发;
- 容灾:字体版本漂移时触发自动重训/告警,防止映射表失效造成脏数据入库。
答案
思路四步:① 下载 woff → ② 提取每个 glyph 并生成归一化位图 → ③ 对未知字形做 OCR 得真实字符 → ④ 建立「glyph_id→真实字符」映射表,回写 HTML 时替换。
Python 伪代码(单线程版,可直接扩展到协程/消息队列):
# -*- coding: utf-8 -*-
import re, io, requests, hashlib, redis, json
from fontTools.ttLib import TTFont
from PIL import Image, ImageDraw, ImageFont
import easyocr # pip install easyocr
# 全局缓存
rd = redis.Redis(decode_responses=True)
OCR_READER = easyocr.Reader(['en'], gpu=False) # 数字场景足够
def download_font(css_url):
"""从 CSS 里拿到 woff 地址并下载"""
css = requests.get(css_url, timeout=5).text
woff_url = re.search(r'url\((.*?\.woff)\)', css).group(1)
if not woff_url.startswith('http'):
woff_url = 'https:' + woff_url
return requests.get(woff_url, timeout=5).content
def glyph_to_hash(glyph):
"""把字形画成 64×64 二值图,算 perceptual hash"""
img = Image.new('L', (64, 64), 255)
draw = ImageDraw.Draw(img)
# 将 glyph 轮廓点转成 SVG 路径再画,简化:直接用 fontTools 的 pen
pen = ImageDraw.Pen(draw)
glyph.draw(pen)
img = img.resize((32, 32), Image.LANCZOS)
# 简单 dhash
hash_str = ''
for i in range(32):
for j in range(31):
hash_str += '1' if img.getpixel((j, i)) > img.getpixel((j+1, i)) else '0'
return hashlib.md5(hash_str.encode()).hexdigest()
def ocr_glyph(img):
"""对单张字形图做 OCR,返回最可能的字符"""
result = OCR_READER.readtext(np.array(img), detail=0, allowlist='01234567890.')
return result[0] if result else None
def build_map(woff_bytes):
font = TTFont(io.BytesIO(woff_bytes))
glyf_table = font['glyf']
cmap = font.getBestCmap() # unicode -> glyphID
glyph2char = {} # 我们要的输出:glyphID -> real_char
for unicode, glyphID in cmap.items():
glyph = glyf_table[glyphID]
if glyph.numberOfContours == 0: # 空白字形
continue
hash_val = glyph_to_hash(glyph)
real_char = rd.hget('glyph_hash', hash_val)
if real_char is None:
# 缓存未命中,OCR 识别
img = render_glyph_to_image(glyph) # 同上,略
real_char = ocr_glyph(img)
if real_char:
rd.hset('glyph_hash', hash_val, real_char)
if real_char:
glyph2char[glyphID] = real_char
return glyph2char
def decrypt_html(html, woff_bytes):
"""根据映射表把 html 里的伪 Unicode 换回真实字符"""
font = TTFont(io.BytesIO(woff_bytes))
cmap = font.getBestCmap()
glyph2char = build_map(woff_bytes)
def repl(m):
unicode_int = ord(m.group(0))
glyphID = cmap.get(unicode_int)
return glyph2char.get(glyphID, m.group(0))
return re.sub(r'[\uE000-\uF8FF]', repl, html) # 私有区段
# 使用示例
if __name__ == '__main__':
css_url = 'https://example.com/font.css'
woff = download_font(css_url)
raw_html = requests.get('https://example.com/item/123', headers={'User-Agent': 'Mozilla/5.0'}).text
clean_html = decrypt_html(raw_html, woff)
# 后续用 pyquery/bs4 提取价格、销量等字段入库
关键工程化增强(面试可主动补充)
- 并发:把
build_map做成 Kafka 流任务,新字体版本号作为 key,防止重复识别; - 漂移检测:对同一 hash 对应多个不同 real_char 触发告警,人工复核;
- 数字专用模型:用 0-9+小数点 10 类样本微调 MobileNet,准确率>99%,耗时<10 ms;
- 合规声明:采集仅用于公开比价分析,字体文件及 hash 库不对外提供,遵守《反不正当竞争法》及 robots 协议。
拓展思考
-
如果平台把字形做轻微随机扰动(贝塞尔点±1),hash 会失效,怎么办?
→ 升级为“形状上下文+弹性匹配”或“Siamese CNN”做相似度度量,把“未知字形”与基准库做最近邻检索,阈值 0.95 以上即认为同一字符。 -
遇到「分段字体」:价格用两套字体,整数和小数点分开映射,如何联动?
→ 在 OCR 阶段把整串区域截图识别,再用正则(\d+\.\d+)校验,反向对齐到 glyph 序列,确保映射自洽。 -
法律红线:
- 字体文件受《著作权法》保护,不可二次分发;
- 若平台在 ToS 明确禁止“批量抓取”,需评估合同效力;
- 个人信息(手机号、ID)即使解密成功也应脱敏,符合《个人信息保护法》。
-
采集链路稳定性:
把字体版本号写入 Hive 分区字段,一旦映射表失效可快速回滚;同时监控“解密失败率”指标,超过 5% 自动熔断并报警,避免脏数据污染下游 AI 训练。