【PyTest】玩转HTML报告:修改、汉化和优化
warning:
这篇文章距离上次修改已过185天,其中的内容可能已经有所变动。
# 导入必要的模块
import os
from pathlib import Path
from typing import List
# 定义修改HTML报告的函数
def modify_html_report(html_report_path: str, custom_css_path: str = None, custom_js_path: str = None, translation_dict: dict = None) -> None:
"""
修改HTML报告文件,根据指定的CSS、JS和翻译字典进行自定义。
:param html_report_path: HTML报告文件的路径。
:param custom_css_path: 自定义CSS文件的路径。
:param custom_js_path: 自定义JS文件的路径。
:param translation_dict: 翻译词典,键为原文,值为翻译后的文本。
"""
# 读取原始HTML内容
with open(html_report_path, 'r', encoding='utf-8') as file:
html_content = file.read()
# 如果有CSS文件,插入到HTML中
if custom_css_path and os.path.isfile(custom_css_path):
with open(custom_css_path, 'r', encoding='utf-8') as css_file:
css_content = css_file.read()
html_content = html_content.replace('</head>', f'<style type="text/css">{css_content}</style></head>')
# 如果有JS文件,在body结束前插入
if custom_js_path and os.path.isfile(custom_js_path):
with open(custom_js_path, 'r', encoding='utf-8') as js_file:
js_content = js_file.read()
html_content = html_content.replace('</body>', f'{js_content}</body>')
# 如果有翻译字典,进行翻译替换
if translation_dict:
for original, translated in translation_dict.items():
html_content = html_content.replace(original, translated)
# 写入修改后的HTML内容
with open(html_report_path, 'w', encoding='utf-8') as file:
file.write(html_content)
# 示例调用
html_report_path = 'path/to/report.html'
custom_css_path = 'path/to/custom.css'
custom_js_path = 'path/to/custom.js'
translation_dict = {'Failed': '失败', 'Error': '错误', ...} # 这里应包含所有需要翻译的文本
modify_html_report(html_report_path, custom_css_path, custom_js_path, translation_dict)
这个示例代码定义了一个modify_html_report
函数,它接受HTML报告文件路径、自定义CSS文件路径、自定义JavaScript文件路径以及翻译字典作为参数。函数读取原始HTML内容,根据提供的文件路径插入自定义CSS和JavaScript,并对HTML中的特定文本进行翻译。最后,函数将修改后的HTML内容写回原报告文件。这个函数可以作为模板,用于自定义和汉化HTML报告。
评论已关闭