HTML 如何转 Markdown

标注:将多个 HTML 文件转换后合并到一个 .md 文件中

python代码附带如下:(使用下面代码轻松转)

python 复制代码
from markdownify import markdownify as md
import os
from pathlib import Path
import chardet

def 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:
                continue
        return (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_dir

    os.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'] += 1
                html_path = os.path.join(root, filename)
                print(f"正在处理: {html_path}")

                success, result = convert_html_to_markdown(html_path)

                if success:
                    stats['success'] += 1
                    encoding = detect_file_encoding(html_path)
                    stats['encodings'][encoding] = stats['encodings'].get(encoding, 0) + 1

                    with 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'] += 1
                    print(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的环境

  1. 安装python(手动补上环境变量)
  2. 执行python包:pip install markdownify chardet

2. 准备输入输出目录(HTML或者HTM文件)

1. 在你电脑上准备一个文件夹,里面放几个 .html.htm 文件

比如:

复制代码
makefile

D:\test_htmls\
2. 再准备一个输出文件夹(Markdown 会写到这):
复制代码
makefile

D:\test_markdown_output\

3. 使用方法

1. 编辑脚本末尾的路径:

找到下面两行,把路径替换为你本地的目录路径:

复制代码
python

input_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 脚本:

复制代码
bash

python your_script_name.py

你会看到类似:

复制代码
makefile

正在处理: D:\test_htmls\sample.html
=== 转换结果汇总 ===
总文件数: 1
成功: 1
失败: 0
输出目录: D:\test_markdown_output

4. 输出结果

  • 会在 output_directory 中保留输入目录的结构;
  • 所有 .html.htm 文件会被转换为 .md 文件;
  • 编码会自动检测处理,不容易出乱码;
  • 最后会打印汇总统计,比如成功/失败数量、使用的编码分布等。
相关推荐
麦兜*2 小时前
Spring Boot集成方案 + Elasticsearch向量检索,语义搜索核弹
java·spring boot·python·spring·elasticsearch·spring cloud·系统架构
仪器科学与传感技术博士2 小时前
python:讲懂决策树,为理解随机森林算法做准备,以示例带学习,通俗易懂,容易理解和掌握
python·算法·决策树
小坏坏的大世界3 小时前
C++中多线程和互斥锁的基本使用
开发语言·c++
路由侠内网穿透3 小时前
本地部署 SQLite 数据库管理工具 SQLite Browser ( Web ) 并实现外部访问
运维·服务器·开发语言·前端·数据库·sqlite
王者鳜錸3 小时前
PYTHON从入门到实践-18Django模版渲染
开发语言·python·django
Hard but lovely4 小时前
C++ STL--> vector的模拟实现!
开发语言·c++
hweiyu004 小时前
IDEA搭建GO环境
开发语言·后端·golang·intellij-idea·idea·intellij idea
归辞...4 小时前
「iOS」————单例与代理
开发语言·javascript·ios
l1t5 小时前
利用DeepSeek改写并增强测试Duckdb和sqlite的不同插入方法性能
python·sql·sqlite·duckdb