In this article, we will generate and use HTML documents in python by using tinyhtml module of python
How to write raw HTML to file using python?
You can generate HTML documents in Python by manually creating the HTML string and writing it to a file with a .html extension. Here’s a simple example that generates HTML documents with a title, header, and body:
#Storing the entire HTML document in html variable
html = """
<html>
<head>
<title>AskPython</title>
</head>
<body>
<h1>Welcome to AskPython</h1>
<p>This is an article about generating HTML docs using python</p>
</body>
</html>
"""
#using file management
with open("askpython.html", "w") as f:
f.write(html)
In the above code, we have used the open() function with “w” mode which writes HTML in the file “askpython.html” this will create a file named “askpython.html” in the same directory with the following content:
<html>
<head>
<title>AskPython</title>
</head>
<body>
<h1>Welcome to AskPython</h1>
<p>This is an article about generating HTML docs using python</p>
</body>
</html>
To know more about file handling visit the article Python File Handling
The tinyhtml module for HTML documents
tinyhtml is a python library that safely renders and provides a very basic HTML parsing functionality compact HTML5 from Python expressions. In this article we will install and use some useful functions provided by the tinyhtml library : html() , render() , h() and frag()
Installing tinyhtml
We will start by installing tinyhtml in our python environment using pip
pip install tinyhtml
1. Using html() and render() to declare and render basic HTML
html() is used to declare HTML documents. Let’s start with a straightforward example:
from tinyhtml import html
html_content = html(lang="en")()
print(html_content.render())
Explanation:
- The code creates an HTML
htmlelement with thelangattribute set to"en". - The
()after thehtmlfunction call indicates that there are no child elements to add to thehtmlelement. Therefore output contains just one HTML tag with an attribute - The
render() method is then called on thehtml_contentvariable, which converts thehtmlelement to a string of HTML. - Finally, the resulting HTML string is printed to the console using the
printfunction.
Output:
<!DOCTYPE html><html lang="en"></html>
2. Using the h() Function to Generate HTML Code in Python
The function h() is the most useful function, it provides for the rendering of attributes, common components, and void/self-closing elements.
Example:
from tinyhtml import html , h
html_content = html(lang="en")(
h("h1")("Lorem ipsum"),
h("p")("dolor sit amet."),
h ("br")
)
print(html_content.render())
Explanation:
- The code above creates an HTML document string containing an
htmlelement inside which, there are three child elements:- An
h1element with the text “Lorem ipsum”. - A
pelement with the text “dolor sit amet.” - A
brelement, which represents a line break in HTML.
- An
- The
hfunction is used to create theh1andpelements, and thebrelement is created directly using the HTML tag. - The
rendermethod is called on thehtml_contentvariable, which converts thehtmlelement and its child elements to a string of HTML and the resulting HTML string is printed using theprintfunction.
Output:
<!DOCTYPE html><html lang="en"><h1>Lorem ipsum</h1><p>dolor sit amet.</p><br></html>
The output contains an HTML document string containing an html element with the lang attribute set to "en", an h1 element with the text “Lorem ipsum”, a p element with the text “dolor sit amet.”, and a br element.
3. Using frag() function to generate fragments of HTML code
The function frag() is used to circulate sets of elements.
from tinyhtml import h ,frag
content = frag(
h("h1")("Lorem ipsum"),
h("p")("dolor sit amet."),
)
print(content.render())
Explanation:
- The code creates a fragment of HTML containing an
h1element with the text “Lorem ipsum” and apelement with the text “dolor sit amet.”. - The
hfunction is used to create theh1andpelements. - The
fragfunction is then called with two arguments – theh1andpelements created earlier. This creates a fragment of HTML that contains both elements. - The
rendermethod is called on thecontentvariable and the resulting string is printed.
Output:
<h1>Lorem ipsum</h1><p>dolor sit amet.</p>
The output is an HTML fragment string containing an h1 element with the text “Lorem ipsum” and a p element with the text “dolor sit amet.”.
4. Adding conditional statements
You can use conditional statements to generate data according to certain external conditions
from tinyhtml import h
score = input("Input your score(out of 100):")
passing_marks = 33
conditional_html = h("h1")(
h("p")("Passed")
if int(score) > passing_marks
else "Failed",
h("p")("Thank you!")
)
print(conditional_html)
Explanation:
- The code prompts the user to input their score out of 100, with the input value being stored in the
scorevariable. The passing marks are set to 33. - The code then creates an HTML document string containing an
h1element and two childpelements. - The child element
phas the text “Passed” if thescorevariable, after being converted to an integer, is greater than 33 (passing_marks). - If the
scorevariable is less than or equal to thepassing_marks, then the text “Failed” is used instead of “Passed”.
Output:
Input your score(out of 100):45
<h1><p>Passed</p><p>Thank you!</p></h1>
5. Adding class to the tags
To initialize a class, we employ the “klass” operator. A trailing underscore is also added to additional labels that may match the names of Python-reserved keywords.
from tinyhtml import h
html_doc = h("h1")(
h("p" , klass = "p1")("Sample text"),
h("input" , for_ = "firstName")()
)
print(html_doc)
Here we have assigned class “p1” to the paragraph tag and used “klass” instead of “class”. For the input tag, we have used “for_” which is for the label “for” which is a reserved keyword in python. You can see the correct HTML in the given output
Output:
<h1><p class="p1">Sample text</p><input for="firstName"></input></h1>
Conclusion
In this article, we’ve created HTML documents using tinyhtml. We’ve provided a few basic tags that you can alter as necessary. Also, read Pandas to html.


