一、环境准备与基础用法
1.1 安装markdown库
bash
pip install markdown
1.2 基础转换示例
python
import markdown
md_content = """
# Hello World
**Python** Markdown转换演示:
- 列表项1
- 列表项2
"""
html_content = markdown.markdown(md_content)
print(html_content)
输出结果:
html
<h1>Hello World</h1>
<p><strong>Python</strong> Markdown转换演示:</p>
<ul>
<li>列表项1</li>
<li>列表项2</li>
</ul>
二、文件级转换实践
2.1 文件读写转换
python
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 常用扩展模块
python
extensions = [
'tables', # 表格支持
'fenced_code', # 代码块
'nl2br', # 换行转换
'sane_lists' # 智能列表
]
html = markdown.markdown(md_text, extensions=extensions)
3.2 代码高亮扩展
python
html = markdown.markdown(md_text,
extensions=['codehilite'],
extension_configs={
'codehilite': {
'linenums': True,
'css_class': 'highlight'
}
})
需配合Pygments使用:
bash
pip install pygments
四、安全防护与输出处理
4.1 安全模式
python
# 过滤潜在危险标签
safe_html = markdown.markdown(raw_input, safe_mode=True)
4.2 白名单过滤
python
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样式表
python
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模板
python
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)
六、实用案例:完整转换脚本
python
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()
使用方式:
bash
python converter.py input.md -o output.html
常见问题排查
-
编码问题:
- 始终指定文件编码为utf-8
pythonopen(file, 'r', encoding='utf-8')
-
扩展加载失败:
- 确认扩展名称拼写正确
- 检查是否需要额外依赖(如codehilite需要Pygments)
-
样式不生效:
- 检查CSS路径是否正确
- 验证HTML结构完整性
- 使用浏览器开发者工具调试样式
通过本指南,您可掌握从基础转换到安全防护、样式定制的完整工作流。建议根据实际需求组合不同的扩展模块,并通过模板引擎实现更复杂的文档生成需求。