概述
最近有一個需求,在界面對表格進行自動截圖,然后將圖片存起來
方案
第一種: selenium +chromedirver + pillow
使用自動化工具,網(wǎng)頁截圖, 通過元素定位到具體位置,pillow進行裁剪得出最理想結果,此方案還是存在很大誤差,因為表格數(shù)據(jù)數(shù)量非固定的,計算誤差很大,難以精準
第二種: prettytable + pillow
通過prettytable將數(shù)據(jù)生成簡單表格布局,通過pillow 生成圖片,這個方案簡單容易,但是表格樣式過于丑陋,暫不考慮
第三種: html-table + imgkit
通過html-table將數(shù)據(jù)生成帶樣式的html文件,然后使用imgkit 轉換成圖片,該方案是目前最理想的
實施過程
1、環(huán)境安裝
- python庫安裝
pip insatll html-table==1.0
pip insatll imgkit==1.0.2
- 還需下載一個核心工具wkhtmltopdf
官方途徑下載:https://wkhtmltopdf.org/downloads.html
這個下載可能有點慢,建議從其他途徑下載,由于系統(tǒng)window版的,所以本人從此處下載的http://www.pc6.com/softview/SoftView_559241.html
安裝完成后,需要配置環(huán)境變量
2、demo演示
import imgkit
from HTMLTable import HTMLTable
# 標題
table = HTMLTable(caption='果園收成表')
# 表頭行
table.append_header_rows((
('名稱', '產量 (噸)','增長量 (噸)','增長率 (%)'),
))
# 數(shù)據(jù)行
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',
})
# 統(tǒng)一設置所有單元格樣式,<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',
})
# 遍歷數(shù)據(jù)行,如果增長量為負,標紅背景顏色
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、參數(shù)說明
- 可以通過下面命令查看參數(shù)options使用
wkhtmltoimage -H

- 本人常用參數(shù)
options = {
"enable-local-file-access": None, # html中圖片路徑訪問,必須攜帶該參數(shù),是訪問權限設置
"quality": 80, # 圖片質量比(也是壓縮比),涉及一個圖片大小調整,
"width": 1255, # 圖片的寬
"height": 1255, # 圖片的高
"zoom": 2.1 # 調節(jié)清晰度,數(shù)值越高像素越高,但是也會因圖片width,height值變化而變化
...
#待更新
}
wkhtmltoimg使用遇到的問題
- 問1:html帶有圖片鏈接的,生成圖片時如何生效
1、html的圖片路徑必須是全路徑
2、設置參數(shù),允許訪問路徑
options = {
"enable-local-file-access": None,
}
- 問2:html中使用了echarts插件,圖表不生效或顯示不全問題
1、html的圖表標簽必須設置長和寬
2、echarts的參數(shù)animation設置為false,防止動態(tài)加載導致顯示不全
3、為了js加載完全,可根據(jù)情況增加延時
options = {
"javascript-delay": 3000,
}