概述
最近有一个需求,在界面对表格进行自动截图,然后将图片存起来
方案
第一种: selenium +chromedirver + pillow
使用自动化工具,网页截图, 通过元素定位到具体位置,pillow进行裁剪得出最理想结果,此方案还是存在很大误差,因为表格数据数量非固定的,计算误差很大,难以精准
第二种: prettytable + pillow
通过prettytable将数据生成简单表格布局,通过pillow 生成图片,这个方案简单容易,但是表格样式过于丑陋,暂不考虑
第三种: html-table + imgkit
通过html-table将数据生成带样式的html文件,然后使用imgkit 转换成图片,该方案是目前最理想的
实施过程
1、环境安装
- python库安装
pip insatll html-table==1.0
pip insatll imgkit==1.0.2
- 还需下载一个核心工具wkhtmltopdf
官方途径下载:https://wkhtmltopdf.org/downloads.html
这个下载可能有点慢,建议从其他途径下载,由于系统window版的,所以本人从此处下载的http://www.pc6.com/softview/SoftView_559241.html
安装完成后,需要配置环境变量
2、demo演示
import imgkit
from HTMLTable import HTMLTable
# 标题
table = HTMLTable(caption='果园收成表')
# 表头行
table.append_header_rows((
('名称', '产量 (吨)','增长量 (吨)','增长率 (%)'),
))
# 数据行
table.append_data_rows((
('荔枝', 11, 1, 10),
('芒果', 9, -1, -10),
('香蕉', 6, 1, 20),
))
# 标题样式
table.caption.set_style({
'font-size': '15px',
})
# 表格样式,即<table>标签样式
table.set_style({
'border-collapse': 'collapse',
'word-break': 'keep-all',
'white-space': 'nowrap',
'font-size': '14px',
})
# 统一设置所有单元格样式,<td>或<th>
table.set_cell_style({
'width': "250px",
'border-color': '#000',
'border-width': '1px',
'border-style': 'solid',
'padding': '5px',
})
# 表头样式
table.set_header_row_style({
'color': '#fff',
'background-color': '#48a6fb',
'font-size': '18px',
})
# 覆盖表头单元格字体样式
table.set_header_cell_style({
'padding': '15px',
})
# 调小次表头字体大小
table[1].set_cell_style({
'padding': '8px',
'font-size': '15px',
})
# 遍历数据行,如果增长量为负,标红背景颜色
for row in table.iter_data_rows():
if row[2].value < 0:
row.set_style({
'background-color': '#ffdddd',
})
body = table.to_html()
# html的charset='UTF-8'必须加上,否则中午会乱码
html = "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body>{0}</body></html>".format(body)
# 生成图片
options = {
"enable-local-file-access": None, # html携带图片有访问权限设置
"width": 1255,
"zoom": 2.1 # 越高像素越高
}
# 生成图片
imgkit.from_string(html, 'out.jpg', options=options)
imgkit官方文档:https://github.com/jarrekk/imgkit
3、参数说明
- 可以通过下面命令查看参数options使用
wkhtmltoimage -H

- 本人常用参数
options = {
"enable-local-file-access": None, # html中图片路径访问,必须携带该参数,是访问权限设置
"quality": 80, # 图片质量比(也是压缩比),涉及一个图片大小调整,
"width": 1255, # 图片的宽
"height": 1255, # 图片的高
"zoom": 2.1 # 调节清晰度,数值越高像素越高,但是也会因图片width,height值变化而变化
...
#待更新
}
wkhtmltoimg使用遇到的问题
- 问1:html带有图片链接的,生成图片时如何生效
1、html的图片路径必须是全路径
2、设置参数,允许访问路径
options = {
"enable-local-file-access": None,
}
- 问2:html中使用了echarts插件,图表不生效或显示不全问题
1、html的图表标签必须设置长和宽
2、echarts的参数animation设置为false,防止动态加载导致显示不全
3、为了js加载完全,可根据情况增加延时
options = {
"javascript-delay": 3000,
}