【python】lxml-The E-factory

时间:2023-03-09 04:58:03
【python】lxml-The E-factory

来自:http://lxml.de/tutorial.html

lxml中的E-factory可以用个简单快速的生成XML和HTML

>>> from lxml.builder import E

>>> def CLASS(*args): # class is a reserved word in Python
... return {"class":' '.join(args)} >>> html = page = (
... E.html( # create an Element called "html"
... E.head(
... E.title("This is a sample document")
... ),
... E.body(
... E.h1("Hello!", CLASS("title")),
... E.p("This is a paragraph with ", E.b("bold"), " text in it!"),
... E.p("This is another paragraph, with a", "\n ",
... E.a("link", href="http://www.python.org"), "."),
... E.p("Here are some reservered characters: <spam&egg>."),
... etree.XML("<p>And finally an embedded XHTML fragment.</p>"),
... )
... )
... ) >>> print(etree.tostring(page, pretty_print=True))
<html>
<head>
<title>This is a sample document</title>
</head>
<body>
<h1 class="title">Hello!</h1>
<p>This is a paragraph with <b>bold</b> text in it!</p>
<p>This is another paragraph, with a
<a href="http://www.python.org">link</a>.</p>
<p>Here are some reservered characters: &lt;spam&amp;egg&gt;.</p>
<p>And finally an embedded XHTML fragment.</p>
</body>
</html>