[Tutor] Generating HTML
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Fri Oct 1 22:58:26 CEST 2004
On Fri, 1 Oct 2004, Tony Cappellini wrote:
> It seems as though there is some support for reading and parsing HTML,
> in htmllib and HTMLParser, but are there any tools in the python
> distributions for generating html?
Hi Tony,
Pydoc does HTML generation on the fly; I wonder how it does it! Let's
see..
######
class HTMLDoc(Doc):
"""Formatter class for HTML documentation."""
[some text cut]
def page(self, title, contents):
"""Format an HTML page."""
return '''
<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: %s</title>
</head><body bgcolor="#f0f0f8">
%s
</body></html>''' % (title, contents)
######
They hardcode it, and use simple string interpolation. That's a simple
approach, and might be suitable for what you're doing.
As far as third-party modules go, there's HTMLGen:
http://starship.python.net/crew/friedrich/HTMLgen/html/main.html
You can also generate XHTML with the xml.sax.XMLGenerator helper module:
###
>>> import xml.sax.saxutils
>>> from StringIO import StringIO
>>> myfile = StringIO()
>>> xmlwriter = xml.sax.saxutils.XMLGenerator(out=myfile)
>>> xmlwriter.startDocument()
>>> xmlwriter.startElement("html", {})
>>> xmlwriter.startElement("p", {})
>>> xmlwriter.characters("Hello world!")
>>> xmlwriter.endElement("p")
>>> xmlwriter.endElement("html")
>>> myfile.getvalue()
'<?xml version="1.0" encoding="iso-8859-1"?>\n<html><p>Hello
world!</p></html>'
###
And XMLGenerator guarantees that all the proper string escaping is being
done. So I don't have to worry about silly things like escaping the less
than symbol or ampersand symbols. In the simpler string-interpolation
approach that we used at the beginning, we'd have to worry about that sort
of stuff.
But this is a primitive way to generate XHTML, though; I'm sure that there
are nicer packages out there. I did a Google search and came up with:
http://www.software-facilities.com/textproc-software/py-HyperText.php
Good luck to you!
More information about the Tutor
mailing list