Python利用markdown库实现Markdown到HTML的高效转换(附安全处理与样式扩展)

发布于:2025-02-19 ⋅ 阅读:(28) ⋅ 点赞:(0)

一、环境准备与基础用法

1.1 安装markdown库

pip install markdown

1.2 基础转换示例

import markdown

md_content = """
# Hello World
**Python** Markdown转换演示:
- 列表项1
- 列表项2
"""

html_content = markdown.markdown(md_content)
print(html_content)

输出结果:

<h1>Hello World</h1>
<p><strong>Python</strong> Markdown转换演示:</p>
<ul>
<li>列表项1</li>
<li>列表项2</li>
</ul>

二、文件级转换实践

2.1 文件读写转换

def convert_md_to_html(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as f:
        md_text = f.read()
  
    html_text = markdown.markdown(md_text)
  
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(f"<!DOCTYPE html>\n<html>\n<body>\n{html_text}\n</body>\n</html>")

# 使用示例
convert_md_to_html('document.md', 'output.html')

三、扩展功能深度应用

3.1 常用扩展模块

extensions = [
    'tables',       # 表格支持
    'fenced_code',  # 代码块
    'nl2br',        # 换行转换
    'sane_lists'    # 智能列表
]

html = markdown.markdown(md_text, extensions=extensions)

3.2 代码高亮扩展

html = markdown.markdown(md_text, 
                        extensions=['codehilite'],
                        extension_configs={
                            'codehilite': {
                                'linenums': True,
                                'css_class': 'highlight'
                            }
                        })

需配合Pygments使用:

pip install pygments

四、安全防护与输出处理

4.1 安全模式

# 过滤潜在危险标签
safe_html = markdown.markdown(raw_input, safe_mode=True)

4.2 白名单过滤

from markdown import Extension
from markdown.treeprocessors import Treeprocessor

class SafetyFilter(Treeprocessor):
    def run(self, root):
        for el in root.iter():
            if el.tag not in ['h1', 'p', 'ul', 'li']:
                el.drop_tag()

class SafetyExtension(Extension):
    def extendMarkdown(self, md):
        md.treeprocessors.register(SafetyFilter(), 'safety_filter', 0)

html = markdown.markdown(text, extensions=[SafetyExtension()])

五、样式定制与模板集成

5.1 添加CSS样式表

def wrap_with_style(html_content):
    return f"""<!DOCTYPE html>
<html>
<head>
    <style>
        body {{ max-width: 800px; margin: 20px auto }}
        code {{ background: #f5f5f5; padding: 2px 4px }}
    </style>
</head>
<body>
{html_content}
</body>
</html>"""

5.2 结合Jinja2模板

from jinja2 import Template

template = Template("""
<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
    {% include 'styles.css' %}
</head>
<body>
    {{ content|safe }}
</body>
</html>
""")

rendered = template.render(title="Converted Document", content=html_content)

六、实用案例:完整转换脚本

import markdown
import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('input', help='Input .md file')
    parser.add_argument('-o', '--output', help='Output .html file')
    args = parser.parse_args()

    with open(args.input, 'r') as f:
        converted = markdown.markdown(f.read(),
                                    extensions=['tables', 'fenced_code'],
                                    output_format='html5')
  
    output_file = args.output or args.input.replace('.md', '.html')
    with open(output_file, 'w') as f:
        f.write(f"""<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body>
{converted}
</body>
</html>""")

if __name__ == "__main__":
    main()

使用方式:

python converter.py input.md -o output.html

常见问题排查

  1. 编码问题

    • 始终指定文件编码为utf-8
    open(file, 'r', encoding='utf-8')
    
  2. 扩展加载失败

    • 确认扩展名称拼写正确
    • 检查是否需要额外依赖(如codehilite需要Pygments)
  3. 样式不生效

    • 检查CSS路径是否正确
    • 验证HTML结构完整性
    • 使用浏览器开发者工具调试样式

通过本指南,您可掌握从基础转换到安全防护、样式定制的完整工作流。建议根据实际需求组合不同的扩展模块,并通过模板引擎实现更复杂的文档生成需求。