当物料使用 WebP 动态帧时,如何逐帧扫描?
解读
在 Scrapy 实际抓取中,WebP 动图常被当作单张“图片”下载,但业务方往往要求把每一帧拆出来做 OCR、标签、去重或喂给 CV 模型。
面试官想确认:
- 你是否知道 WebP 的动画容器结构(ANIM、ANMF、VP8/VP8L 块);
- 能否在Scrapy 管道内用纯 Python 或 C 扩展库快速拆帧,而不落地磁盘;
- 是否考虑内存占用、并发安全、异常处理;
- 能否把拆帧结果继续交给下游 Pipeline(例如 PIL、OpenCV、Redis 队列)。
一句话:**“下载后立刻在内存里拆帧,并生成可迭代帧对象”**是得分点。
知识点
- WebP 容器格式:RIFF 头 + VP8X(动画标志位)+ ANIM(全局参数)+ 若干 ANMF(单帧)
- Python 拆帧库:
– pillow-avif-plugin ≥1.4 内置 webp_decoder
– pywebp (google-webpmux 绑定) 提供 WebPAnimDecoder
– webptools 带 webpmux_get_frames - Scrapy 内存管道:重写 ImagesPipeline 的
get_images方法,把response.body直接送进解码器,避免Image.open只读第一帧 - 逐帧对象设计:用 namedtuple(“WebPFrame”, “idx duration timestamp img_bytes”) 保持轻量
- 并发安全:decoder 实例在 thread-local 中复用,防止多线程崩
- 异常策略:捕获 OSError: truncated WebP 并返回空生成器,让爬虫继续
- 下游对接:把帧序列转成 BytesIO(PNG) 再喂给 Tesseract、Redis、Kafka,避免二次编码损失
答案
- 自定义 WebPFramesPipeline 继承 ImagesPipeline
- 在
file_downloaded(self, response, request, info)里判断image/webp且检查 VP8X 动画位:from PIL import Image, features if features.check('webp_anim'): decoder = Image.open(BytesIO(response.body)) if getattr(decoder, 'is_animated', False): for idx in range(decoder.n_frames): decoder.seek(idx) frame = decoder.convert('RGB') yield WebPFrame(idx, decoder.info['duration'], None, image_to_bytes(frame, 'PNG')) - 若 PIL 版本低,改用 pywebp:
from webm import WebPAnimDecoder dec = WebPAnimDecoder(BytesIO(response.body)) while True: try: arr, timestamp = dec.get_next() yield WebPFrame(dec.curr_frame, dec.duration, timestamp, array_to_png_bytes(arr)) except StopIteration: break - 把生成器打包成 Item 字段
frame_list,后续 Pipeline 直接迭代,不落盘 - 在
settings.py里调高 DOWNLOAD_TIMEOUT 与 CONCURRENT_REQUESTS,防止动图过大导致超时
拓展思考
- 分布式拆帧:把原始 WebP 推到 Scrapy-Redis 的
webp_queue,用 Frp + GPU 容器 做批量拆帧,回写帧 Item 到frame_result队列,实现计算与 IO 分离 - 增量更新:在 ANMF 块里取 frame_checksum,与 Redis 布隆过滤器比对,只处理新增帧,秒级增量
- 反爬对抗:部分站点把关键帧藏在 WebP 的 ALPH (alpha) 块 里,需用 libwebpjs 在 Splash 先渲染再抓屏;此时拆帧逻辑后移到 Splash Lua 脚本,Scrapy 只负责调度
- 性能极限:单进程拆帧 CPU 瓶颈明显,可预编译 libwebp-demux 为 Cython extension,在
twisted.reactor的 ThreadPool 中跑,QPS 提升 4~6 倍