在python中,生成HTML文档的最优雅方式是什么.我目前手动将所有标签附加到一个巨大的字符串,并将其写入文件.有更优雅的方式吗?
Joh*_*nal 48
我发现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()
Run Code Online (Sandbox Code Playgroud)
它读起来像html,还有一个额外的好处,就是你不必关闭标签.
Eri*_*erg 30
我建议使用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)
Run Code Online (Sandbox Code Playgroud)
如果你在磁盘上有模板,那就更简单了 - 检查一下render_to_string函数,该函数可以从预定义的搜索路径列表中加载来自磁盘的模板,填充来自dictory的数据并渲染为字符串 - 所有这些都在一个函数调用中.
Mik*_*son 14
还有一个不错的现代替代方案:: https airium
: //pypi.org/project/airium/
from airium import Airium
a = Airium()
a('<!DOCTYPE html>')
with a.html(lang="pl"):
with a.head():
a.meta(charset="utf-8")
a.title(_t="Airium example")
with a.body():
with a.h3(id="id23409231", klass='main_header'):
a("Hello World.")
html = str(a) # casting to string extracts the value
print(html)
Run Code Online (Sandbox Code Playgroud)
打印这样一个字符串:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8" />
<title>Airium example</title>
</head>
<body>
<h3 id="id23409231" class="main_header">
Hello World.
</h3>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
最大的优点airium
是 - 它还有一个反向翻译器,可以从 html 字符串构建 python 代码。如果您想知道如何实现给定的 html 片段 - 翻译器会立即为您提供答案。
它的存储库包含使用airium
in: tests/documents自动翻译的示例页面的测试。一个很好的起点(任何现有的教程) - 是这个:tests/documents/w3_architects_example_original.html.py
如果您正在构建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')
Run Code Online (Sandbox Code Playgroud)
打印以下内容:
<html><body><div class="foo"><span class="bar">Hello World</span></div></body></html>
Run Code Online (Sandbox Code Playgroud)
我建议使用xml.dom来做到这一点.
http://docs.python.org/library/xml.dom.html
阅读本手册页,它提供了构建XML(以及XHTML)的方法.它使所有XML任务变得更加容易,包括添加子节点,文档类型,添加属性,创建文本节点.这应该能够帮助您完成创建HTML的绝大部分工作.
它对于分析和处理现有的xml文档也非常有用.
希望这可以帮助
PS
这是一个应该帮助您应用语法的教程
http://www.postneo.com/projects/pyxml/