HTML 如何转 Markdown
标注:将多个 HTML 文件转换后合并到一个 .md
文件中
python代码附带如下:(使用下面代码轻松转)
from markdownify import markdownify as md
import os
from pathlib import Path
import chardetdef detect_file_encoding(file_path):"""检测文件编码:param file_path: 文件路径:return: 检测到的编码"""with open(file_path, 'rb') as f:raw_data = f.read(10000)result = chardet.detect(raw_data)return result['encoding']def convert_html_to_markdown(html_file_path):"""转换HTML文件为Markdown(自动处理编码):param html_file_path: HTML文件路径:return: (是否成功, 转换后的Markdown内容或错误信息)"""try:encoding = detect_file_encoding(html_file_path)if not encoding:encoding = 'euc-jp'with open(html_file_path, 'r', encoding=encoding, errors='replace') as f:html_content = f.read()# 转换为 Markdown,去掉加粗和斜体的标记markdown_content = md(html_content, strong_em_symbol='', em_symbol='')# 3.1 如果包含特定内容则移除if 'General - Move/Set - MOV' in markdown_content:markdown_content = markdown_content.replace('General - Move/Set - MOV', '')return (True, markdown_content)except UnicodeDecodeError:encodings_to_try = ['gb2312', 'gbk', 'gb18030', 'euc-jp', 'shift_jis', 'utf-8']for enc in encodings_to_try:try:with open(html_file_path, 'r', encoding=enc) as f:html_content = f.read()markdown_content = md(html_content, strong_em_symbol='', em_symbol='')if 'General - Move/Set - MOV' in markdown_content:markdown_content = markdown_content.replace('General - Move/Set - MOV', '')return (True, markdown_content)except:continuereturn (False, f"无法解码文件: {html_file_path}")except Exception as e:return (False, f"转换失败 {html_file_path}: {str(e)}")def batch_convert_html_to_md(input_dir, output_dir=None):"""批量转换目录下的HTML文件为Markdown,并合并为一个md文件:param input_dir: HTML文件所在目录:param output_dir: 输出目录"""if output_dir is None:output_dir = input_diros.makedirs(output_dir, exist_ok=True)merged_md_path = os.path.join(output_dir, "all_in_one.md")# 清空合并输出文件with open(merged_md_path, 'w', encoding='utf-8') as f:f.write("# 合并文档\n\n")stats = {'total': 0,'success': 0,'failed': 0,'encodings': {}}for root, _, files in os.walk(input_dir):for filename in files:if filename.lower().endswith(('.htm', '.html')):stats['total'] += 1html_path = os.path.join(root, filename)print(f"正在处理: {html_path}")success, result = convert_html_to_markdown(html_path)if success:stats['success'] += 1encoding = detect_file_encoding(html_path)stats['encodings'][encoding] = stats['encodings'].get(encoding, 0) + 1with open(merged_md_path, 'a', encoding='utf-8') as f:# f.write(f"\n\n## 来自文件: {filename}\n\n")name_without_ext = Path(filename).stem # 去掉 .htm/.html 扩展名f.write(f"\n\n## {name_without_ext}\n\n")f.write(result)f.write("\n\n---\n\n")else:stats['failed'] += 1print(f"错误: {result}")print("\n=== 转换结果汇总 ===")print(f"总文件数: {stats['total']}")print(f"成功: {stats['success']}")print(f"失败: {stats['failed']}")print("\n编码分布:")for enc, count in stats['encodings'].items():print(f"{enc or '未知'}: {count} 个文件")print(f"\n输出文件: {os.path.abspath(merged_md_path)}")if __name__ == "__main__":input_directory = r"D:\\YH_Project\\html@md\\html file" # 替换为你的 HTML 目录output_directory = r"D:\\YH_Project\\html@md\\markdown_output" # 替换为输出目录batch_convert_html_to_md(input_directory, output_directory)
1. 首先要有python的环境
- 安装python(手动补上环境变量)
- 执行python包:pip install markdownify chardet
2. 准备输入输出目录(HTML或者HTM文件)
1. 在你电脑上准备一个文件夹,里面放几个 .html
或 .htm
文件
比如:
makefileD:\test_htmls\
2. 再准备一个输出文件夹(Markdown 会写到这):
makefileD:\test_markdown_output\
3. 使用方法
1. 编辑脚本末尾的路径:
找到下面两行,把路径替换为你本地的目录路径:
pythoninput_directory = r"D:\\soft\\code\\py_code\\testpy\\2052\\2052" # HTML文件所在目录
output_directory = r"D:\\soft\\code\\py_code\\testpy\\markdown_output" # 输出Markdown目录
2. 运行脚本
用命令行运行这个 .py
脚本:
bashpython your_script_name.py
你会看到类似:
makefile正在处理: D:\test_htmls\sample.html
=== 转换结果汇总 ===
总文件数: 1
成功: 1
失败: 0
输出目录: D:\test_markdown_output
4. 输出结果
- 会在
output_directory
中保留输入目录的结构; - 所有
.html
或.htm
文件会被转换为.md
文件; - 编码会自动检测处理,不容易出乱码;
- 最后会打印汇总统计,比如成功/失败数量、使用的编码分布等。