使用dataframe_image导出样式化Dataframe报SyntaxError: not a PNG file错误
问题分析与解决方案
突然失效的可能原因
- 依赖版本冲突:dataframe_image默认依赖selenium、ChromeDriver和pandas,近期这些库的版本更新可能破坏了HTML转PNG的流程,导致生成的文件并非有效PNG格式。
- 浏览器驱动不匹配:本地Chrome浏览器版本更新后,ChromeDriver版本未同步,导致截图操作失败,生成损坏的文件。
- 样式代码兼容性:你的
highlight_rows函数可能在pandas版本更新后出现兼容性问题,生成的HTML结构异常,进而引发截图失败。 - 环境权限问题:系统更新或权限变更导致文件写入不完整,最终生成的PNG文件损坏。
无需HTML导出带样式DataFrame图片的替代方案
方案1:回退dataframe_image到稳定版本
如果之前有可用的稳定版本,直接回退即可:
pip install dataframe_image==[你之前使用的版本号]
同时确保依赖的selenium、ChromeDriver版本和之前一致。
方案2:使用Plotly绘制带样式表格并导出
Plotly支持创建带自定义样式的表格,可直接导出为PNG:
import plotly.graph_objects as go from datetime import datetime from PIL import Image # 构建带样式的表格 fig = go.Figure(data=[go.Table( header=dict(values=list(DATAFINAL.columns), fill_color='paleturquoise', align='left'), cells=dict(values=[DATAFINAL[col] for col in DATAFINAL.columns], # 替换为你的行高亮逻辑 fill_color=[['lightblue' if your_condition else 'white' for _ in range(len(DATAFINAL))] for col in DATAFINAL.columns], align='left')) ]) # 导出并打开图片 now = str(datetime.now()) filename = f"Extracciones-{now[:10]}.png" fig.write_image(filename) Image.open(filename).show()
注:需提前安装依赖:pip install plotly kaleido
方案3:使用matplotlib手动构建带样式表格
代码量稍大但完全可控,可自定义所有样式:
import matplotlib.pyplot as plt from datetime import datetime from PIL import Image now = str(datetime.now()) filename = f"Extracciones-{now[:10]}.png" # 创建画布与轴 fig, ax = plt.subplots(figsize=(10, len(DATAFINAL)*0.5)) ax.axis('tight') ax.axis('off') # 生成表格 table = ax.table(cellText=DATAFINAL.values, colLabels=DATAFINAL.columns, cellLoc='left', loc='center') # 应用行高亮样式 for i in range(len(DATAFINAL)): # 替换为你的行高亮判断逻辑 if your_condition: for j in range(len(DATAFINAL.columns)): table[(i+1, j)].set_facecolor('lightblue') # 调整表格样式 table.auto_set_font_size(False) table.set_fontsize(10) table.scale(1.2, 1.2) # 保存并打开图片 plt.savefig(filename, bbox_inches='tight', dpi=150) plt.close() Image.open(filename).show()
原问题修复建议
如果想继续使用dataframe_image默认流程:
- 检查ChromeDriver版本与本地Chrome是否匹配,下载对应版本的驱动替换。
- 验证
highlight_rows函数的返回值是否符合pandas style要求(比如返回background-color: #xxx这类CSS字符串)。 - 尝试重装所有依赖:
pip uninstall dataframe_image selenium -y && pip install dataframe_image selenium
内容的提问来源于stack exchange,提问作者Agustin Gonzalez
相关产品推荐
相关产品推荐

