在Python中生成HTML文档

102 投票
8 回答
142672 浏览
提问于 2025-04-16 21:50

在Python中,生成HTML文档最优雅的方法是什么?我现在是手动把所有的标签拼接成一个大字符串,然后把它写入一个文件。有没有更优雅的方法来做到这一点?

8 个回答

17

如果你在制作HTML文档,我强烈建议使用模板系统(比如jinja2),就像其他人提到的那样。如果你需要一些低级别的HTML片段生成(可能是作为你模板的输入),那么xml.etree这个包是Python的标准库,可能会很适合你的需求。

import sys
from xml.etree import ElementTree as ET

html = ET.Element('html')
body = ET.Element('body')
html.append(body)
div = ET.Element('div', attrib={'class': 'foo'})
body.append(div)
span = ET.Element('span', attrib={'class': 'bar'})
div.append(span)
span.text = "Hello World"

if sys.version_info < (3, 0, 0):
    # python 2
    ET.ElementTree(html).write(sys.stdout, encoding='utf-8',
                               method='html')
else:
    # python 3
    ET.ElementTree(html).write(sys.stdout, encoding='unicode',
                               method='html')

输出如下:

<html><body><div class="foo"><span class="bar">Hello World</span></div></body></html>
40

我建议你使用Python中很多现成的模板语言,比如Django自带的那个模板引擎(你不需要使用Django的其他功能也可以单独用它的模板引擎)。你可以在谷歌上搜索,会找到很多其他的模板实现。

我发现学习一个模板库有很多好处——每当你需要生成电子邮件、HTML页面、文本文件或类似的东西时,你只需写一个模板,使用你的模板库加载它,然后让模板代码生成最终的产品。

这里有一些简单的代码可以帮助你入门:

#!/usr/bin/env python

from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django

# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""

t = Template(template)
c = Context({"title": "title from code",
             "mystring":"string from code"})
print t.render(c)

如果你的模板保存在磁盘上,那就更简单了——可以看看Django 1.7中的 render_to_string 函数,它可以从预定义的搜索路径中加载磁盘上的模板,用字典中的数据填充,然后一次性渲染成字符串。(这个功能在Django 1.8后被移除了,可以查看 Engine.from_string 来了解类似的操作)

82

你可以使用yattag来优雅地完成这个任务。顺便说一下,我是这个库的作者。

from yattag import Doc

doc, tag, text = Doc().tagtext()

with tag('html'):
    with tag('body'):
        with tag('p', id = 'main'):
            text('some text')
        with tag('a', href='/my-url'):
            text('some link')

result = doc.getvalue()

它的写法像HTML,而且还有一个好处,就是你不需要关闭标签。

撰写回答