使用lxml提取CAPTCHA时Pillow抛出无法识别图像文件的OSError
解决PIL读取CAPTCHA时抛出无法识别图像文件的问题
故障核心原因
从代码逻辑、Python版本兼容性、DOM选择规则三个维度可直接定位报错源头:
- 版本语法不兼容:
img_data.decode('base64')是Python2的遗留写法,Python3环境下字符串类型不存在该解码方法,无法输出合法的图像二进制流 - 字符串切割逻辑错误:页面内嵌base64图像的
src遵循标准data URI格式,即data:image/png;base64,编码内容,分隔符为逗号而非连字符,用partition('-')切割无法提取到纯base64数据 - 节点匹配无校验:固定通过
div img选择CAPTCHA节点时,若页面结构变动取到普通装饰图、空节点,拿到的src值根本不是内嵌base64格式的图像数据
分步修复方案
1. 替换为Python3兼容的Base64解码逻辑
用标准库base64模块完成解码操作,替换原有的字符串解码写法:
import base64 binary_img_data = base64.b64decode(img_base64_str)
2. 修正data URI的拆分规则
按照标准data URI的格式,以逗号为分隔符拆出头字段和实际编码串,避免错误切割:
img_src = tree.cssselect('div img')[0].get('src') # 仅在存在分隔符时拆分,避免异常 img_base64_str = img_src.split(',', 1)[-1] if ',' in img_src else img_src
3. 增加取值校验逻辑
避免无效值流入下游处理环节,提前拦截异常数据:
img_node_list = tree.cssselect('div img') if not img_node_list: raise RuntimeError("页面未匹配到指定的img节点") img_src = img_node_list[0].get('src', '') # 校验是内嵌base64图像才继续处理 if not img_src.startswith('data:image/'): raise ValueError(f"获取的src值非内嵌base64图像,实际值:{img_src}")
4. 完整修复后的CAPTCHA读取函数
import base64 from io import BytesIO from PIL import Image import lxml.html def get_captcha(html): tree = lxml.html.fromstring(html) img_node_list = tree.cssselect('div img') if not img_node_list: raise RuntimeError("页面未匹配到指定的img节点") img_src = img_node_list[0].get('src', '') if not img_src.startswith('data:image/') or ',' not in img_src: raise ValueError(f"img节点src格式异常,实际值:{img_src}") # 拆分得到纯base64串 img_base64_str = img_src.split(',', 1)[-1] # 清理base64串中可能混入的换行、空格等无效字符 img_base64_str = ''.join(img_base64_str.split()) # 正确解码为二进制 binary_img_data = base64.b64decode(img_base64_str) # 包装为类文件对象传入PIL img = Image.open(BytesIO(binary_img_data)) return img
调试技巧
若修复后仍存在识别问题,可将解码后的二进制数据写入本地临时文件,用图像编辑器打开验证数据合法性:
with open('debug_captcha.png', 'wb') as f: f.write(binary_img_data)
若本地文件打开时报损坏,说明base64字符串存在截断、字符污染问题,可回溯DOM取值环节的原始src值排查长度异常、字符混入问题。
内容的提问来源于stack exchange,提问作者Dzhud
相关产品推荐
相关产品推荐

