Template >

Generating HTML documents in python

Mako for example can be used stand-alone just fine, and I often use it to generate html files (reports from a db and such) Question: I’m hacking a quick and dirty python script to generate some reports as static html files.

Generating HTML documents in python

In python, what is the most elegant way to generate HTML documents. I currently manually append all of the tags to a giant string, and write that to a file. Is there a more elegant way of doing this?

You can use yattag to do this in an elegant way. FYI I’m the author of the library.

from yattag import Doc doc, tag, text = Doc().tagtext() with tag('html'): with tag('body'): with tag('p', text('some text') with tag('a', href='/my-url'): text('some link') result = doc.getvalue() 

It reads like html, with the added benefit that you don’t have to close tags.

I would suggest using one of the many template languages available for python, for example the one built into Django (you don’t have to use the rest of Django to use its templating engine) — a google query should give you plenty of other alternative template implementations.

I find that learning a template library helps in so many ways — whenever you need to generate an e-mail, HTML page, text file or similar, you just write a template, load it with your template library, then let the template code create the finished product.

Читайте также:  Python dataframe получить значение ячейки

Here’s some simple code to get you started:

#!/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 = """    Body with >.  """ t = Template(template) c = Context() print t.render(c) 

It’s even simpler if you have templates on disk — check out the render_to_string function for django 1.7 that can load templates from disk from a predefined list of search paths, fill with data from a dictory and render to a string — all in one function call. (removed from django 1.8 on, see Engine.from_string for comparable action)

If you’re building HTML documents than I highly suggest using a template system (like jinja2) as others have suggested. If you’re in need of some low level generation of html bits (perhaps as an input to one of your templates), then the xml.etree package is a standard python package and might fit the bill nicely.

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=) body.append(div) span = ET.Element('span', attrib=) 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') 

I would recommend using xml.dom to do this.

Read this manual page, it has methods for building up XML (and therefore XHTML). It makes all XML tasks far easier, including adding child nodes, document types, adding attributes, creating texts nodes. This should be able to assist you in the vast majority of things you will do to create HTML.

It is also very useful for analysing and processing existing xml documents.

Here is a tutorial that should help you with applying the syntax

Python HTML generator, I am looking for an easily implemented HTML generator for Python. I found HTML.py, but there is no way to add CSS elements (id, class) for table. … Usage exampleprint DIV('bar', ==>

How to generate a static .html with python

I'm looking for a python solution to create a static .html that can be sent out via email, either attached or embedded in the email (ignore this latter option if it requires a lot more work). I do not have requirements for what regards the layout of the .html. The focus here is in identifying the less painful solution for to generate an offline .html.

A potential solution could be along the lines of the following pseudo-code.

from some_unknown_pkg import StaticHTML # Initialise instance newsletter = StaticHTML() # Append charts, tables and text to blank newsletter. newsletter.append(text_here) newsletter.append(interactive_chart_generated_with_plotly) newsletter.append(more_text_here) newsletter.append(a_png_file_loaded_from_local_pc) # Save newsletter to .html, ready to be sent out. newsletter.save_to_html('newsletter.html') 

Where 'newsletter.html' can be opened in a whatever browser. Just to provide a bit more context, this .html is supposed to be sent out to a few selected people inside my company and contains sensible data. I'm using plotly to generate interactive charts to be inserted in the .html.

Seems package in that answer is exactly you want. Docs: http://www.yattag.org/

Another pretty nice package here.

Start your Python module with by importing sys module and redirect stdout to newsletter.html

import sys sys.stdout = open('newsletter.html','w') 

This will redirect any output generated to the html file. Now, just use the print command in python to transmit html tags to the file. For eg try:

print "" print " 

This is my NewsLetter

" print ""`

This code snippet will create a basic HTML file. Now, you can open this file in any browser. For sending email you can use email and smtplib modules of python.

The Dominate package looks like it provides a simple and intuitive way to create HTML pages. https://www.yattag.org/

Run Python in HTML, Run Python script in HTML using Django. Django is a famous and robust Python-based web development framework. Since it is Python-based, it makes it easier …

What python html generator module should I use in a non-web application?

I'm hacking a quick and dirty python script to generate some reports as static html files.

What would be a good module to easily build static html files outside the context of a web application?

My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to output some html tags).

I found two alternatives on my first goolge search:

Also, I feel that using a templating engine would be over-****, but if you differ please say it and why.

Maybe you could try Markdown instead, and convert it to HTML on the fly?

You don't necessarily need something complex - for instance, here's a ~150 line library to generate HTML in a functional manner:

(Full disclosure, I work with the person who originally wrote that version, and I also use it myself.)

Why would a templating engine necessarily be overkill? You don't need the whole web framework just to use the templating engine (at least, for most templating engines). Mako for example can be used stand-alone just fine, and I often use it to generate html files (reports from a db and such)

ElementTree can produce html with some limitations. I'd write it like this:

from xml.etree.ElementTree import ElementTree, Element, SubElement import sys html = Element('html') head = SubElement(html, 'head') style = SubElement(head, 'link') style.attrib = body = SubElement(html, 'body') para = SubElement(body, 'p') para.text = 'Lorem ipsum sit amet' doc = ElementTree(html) doc.write(sys.stdout) 

In case of moderately complex html I'd stick with some templating engine: Jinja2, Mako, Cheetah, just to name a few.

How to generate HTML report in Python?, HTMLTags This fella wrote a module from scratch at this ActiveState community page: HTMLTags - generate HTML in Python (Python …

How to generate HTML report in Python?

I'm looking for a way to print out all my graphs (from matplotlib but already saved as png files) and some data frames in HTML, just like what I usually do with R2HTML .

However I couldn't find detailed descriptions about Python module or functions doing this. Could anyone give me some suggestions?

Looks like a couple of tools exist. I've focused on simple html text writers since I'll be crafting my report page structures completely from scratch. This may differ from the R2HTML which I would guess has a lot of convenience functionality for the sort of things one wishes to stuff into pages from R objects.

HTMLTags This fella wrote a module from scratch at this ActiveState community page: HTMLTags - generate HTML in Python (Python recipe). In the comments I discovered most of the tools I enumerate for this answer.

htmlgen This package looks pretty good and basic. I'm not sure if its the same module described in this old article.

XIST this one looks pretty legit and includes a parser as well. Here's some sample page generation code using the format that you'll need to use to interject all the appropriate python commands inbetween various html elements. The other format utilizes a bunch of nested function calls which will make the python interjection very awkward at best.

with xsc.build() : with xsc.Frag() as myHtmlReport : +xml.XML() +html.DocTypeXHTML10transitional() with html.html() : reportTitle = "My report title" with html.head() : +meta.contenttype() +html.title( reportTitle ) with html.body() : # Insert title header +html.h1( reportTitle ) with html.table() : # Header Row with html.tr() : with html.td() : +xsc.Text( "Col 1 Header" ) with html.td() : +xsc.Text( "Col 2 Header" ) # Data Rows for i in [ 1, 2, 3, 4, 5 ] : with html.tr() : with html.td() : +xsc.Text( "data1_" + str(i) ) with html.td() : +xsc.Text( "data2_" + str(i) ) # Write the report to disk with open( "MyReportfileName.html" , "wb" ) as f: f.write( myHtmlReport.bytes( encoding="us-ascii" ) ) 

libxml2 through Python bindings there's a plain vanilla xmlwriter module, which is probably too generic but good to know about nonetheless. Windows binaries for this package can be found here.

first install the package https://pypi.org/project/html-testRunner/

if __name__ == "__main__": unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner( output= r"here the place where you want to store the your HTML report(mean to say folder path")) 

Creating HTML in python, Dominate is a Python library for creating HTML documents and fragments directly in code without using templating. You could create a simple …

Источник

Оцените статью