#python #前端 通过unity转成html后,会有很多格式化相关字符&空格&换行,也会占据很多空间,可以通过以下脚本,对html进行压缩处理; 在执行脚本之前,需要先确认,是安装了,以下库 ``` shell pip install bs4 pip install BeautifulSoup ``` ## html_minifier.py ``` py # html_minifier.py import re import logging from bs4 import BeautifulSoup, Comment class HTMLMinifier: """ HTML压缩工具类,提供静态方法用于HTML最小化处理 功能: 1. 移除所有HTML注释 2. 压缩空白字符(保留pre/code/textarea内容) 3. 可选移除冗余属性 """ @staticmethod def minify(html_content, remove_redundant_attrs=False): """ 最小化HTML内容 参数: html_content (str): 原始HTML内容 remove_redundant_attrs (bool): 是否移除冗余属性(如type="text/javascript") 返回: str: 压缩后的HTML内容 异常: ValueError: 当输入不是字符串时 """ if not isinstance(html_content, str): raise ValueError("输入必须是字符串类型") try: soup = BeautifulSoup(html_content, 'html.parser') # 移除注释 for comment in soup.find_all(string=lambda text: isinstance(text, Comment)): comment.extract() # 压缩空白 for element in soup.find_all(string=True): if element.parent.name not in ['pre', 'code', 'textarea']: element.replace_with(re.sub(r'\s+', ' ', element.string.strip())) # 可选:移除冗余属性 if remove_redundant_attrs: for tag in soup.find_all(True): if tag.name == 'script' and tag.get('type') == 'text/javascript': del tag['type'] if tag.name == 'style' and tag.get('type') == 'text/css': del tag['type'] if tag.name == 'link' and tag.get('type') == 'text/css': del tag['type'] return str(soup) except Exception as e: logging.error(f"HTML压缩失败: {str(e)}") raise def process_file(input_path, output_path=None, **kwargs): """ 文件处理入口函数 参数: input_path (str): 输入文件路径 output_path (str): 输出文件路径(默认添加.min后缀) **kwargs: 传递给minify的参数 返回: tuple: (压缩后内容, 压缩率) """ try: # 读取输入文件 with open(input_path, 'r', encoding='utf-8') as f: original = f.read() # 处理输出路径 if not output_path: if input_path.endswith('.html'): output_path = input_path.replace('.html', '.min.html') else: output_path = input_path + '.min' # 执行压缩 minified = HTMLMinifier.minify(original, **kwargs) # 写入输出文件 with open(output_path, 'w', encoding='utf-8') as f: f.write(minified) # 计算压缩率 orig_size = len(original.encode('utf-8')) min_size = len(minified.encode('utf-8')) ratio = (orig_size - min_size) / orig_size * 100 logging.info(f"压缩完成: {orig_size} → {min_size} 字节 (缩减 {ratio:.1f}%)") return minified, ratio except Exception as e: logging.error(f"文件处理失败: {str(e)}") raise if __name__ == '__main__': import argparse # 配置日志 logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') # 设置命令行参数 parser = argparse.ArgumentParser(description='HTML文件压缩工具') parser.add_argument('input', help='输入HTML文件路径') parser.add_argument('-o', '--output', help='输出文件路径') parser.add_argument('-r', '--remove-attrs', action='store_true', help='移除冗余属性') args = parser.parse_args() # 执行压缩 try: process_file( args.input, output_path=args.output, remove_redundant_attrs=args.remove_attrs ) except Exception as e: logging.error(f"处理失败: {e}") exit(1) ``` ## 调用方式: 示例,同级目录: ``` shell python .\html_minifier.py .\NewTest_2.html ``` ![[Pasted image 20250620101456.png]]