You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
report_app/app/tools/beautiful_html.py

69 lines
2.2 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import logging
from bs4 import BeautifulSoup
# 获取日志记录器
logger = logging.getLogger(__name__)
# 对日报的html的添加style方便前端渲染
# 日报添加style
def beautiful_report(html):
try:
logger.info("开始给日报添加style")
soup = BeautifulSoup(html, "lxml")
# 找到所有 <p> 标签设置对应的样式
list_p = soup.find_all("p")
for i in range(len(list_p)):
if i == 0:
list_p[i]["class"] = "title"
if i == 1:
list_p[i]["class"] = "subtitle"
# 第3、6、8、10、11、12的标签的字体一致
if i == 2 or i == 5 or i == 7 or i == 9 or i == 11:
list_p[i]["class"] = f"point{i}"
# 第3、4、681012
if i == 3 or i == 4 or i == 6 or i == 8 or i == 10 or i == 12:
list_p[i]["class"] = f"content{i}"
if i == 14 or i == 15 or i == 16 or i == 17:
list_p[i]["class"] = f"table_title{i}"
# 给表格设置样式,由于表格样式统一,因此不用单独设置
list_tables = soup.find_all("table")
# 为每个表格设置统一样式
for i, table in enumerate(list_tables):
# 设置表格整体样式
table["class"] = f"table{i}"
# # 设置表头样式
# for th in table.find_all('th'):
# th['style'] = 'background-color: #4CAF50; color: white; font-weight: bold; padding: 10px; text-align: center;'
#
# # 设置表格行样式
# for tr in table.find_all('tr'):
# tr['style'] = 'border-bottom: 1px solid #ddd;'
#
# # 设置表格单元格样式
# for td in table.find_all('td'):
# td['style'] = 'border: 1px solid #000; padding: 8px; text-align: left; width: 150px; height: 45px;text-align: center;'
html = soup.prettify()
return html
except Exception as e:
logger.exception(f"给日报添加style的方法执行失败{e}")
if __name__ == "__main__":
test_path = r"E:\work_data\work\test_result\日报的html.html"
beautiful_report(test_path)