Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Generate HTML – 3 Easy Ways

#1
Python Generate HTML – 3 Easy Ways

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;310531&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;4&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (4 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (4 votes) </div>
</p></div>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Problem Statement:</strong> How to generate HTML documents in Python?</p>
<p>One of the advantages of opting for <a rel="noreferrer noopener" href="https://blog.finxter.com/python-developer-income-and-opportunity/" data-type="post" data-id="189354" target="_blank">Python</a> as your programming language is that it is one of the most versatile languages, as it emphasizes code readability with extensive use of white space. It supports a large collection of libraries that serves various purposes, which include generating HTML documents in Python. </p>
<p>Before we dive into the libraries, let us learn how we can actually write to an HTML file in Python.</p>
<h2>How to Write to an HTML File in Python?</h2>
<p>You can create and save HTML files with the help of a few simple steps:</p>
<ol>
<li>Use the <code><a href="https://blog.finxter.com/python-open-function/" data-type="post" data-id="24793" target="_blank" rel="noreferrer noopener">open()</a></code> file function to create the HTML file.</li>
<li>Add input data in HTML format into the file with the help of the <code><a href="https://blog.finxter.com/python-how-to-update-and-replace-text-in-a-file/" data-type="post" data-id="528834" target="_blank" rel="noreferrer noopener">write()</a></code> function.</li>
<li>Finally, save and close the file.</li>
</ol>
<p><strong>Example: </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Creating the HTML file
file_html = open("demo.html", "w") # Adding the input data to the HTML file
file_html.write('''&lt;html>
&lt;head>
&lt;title>HTML File&lt;/title>
&lt;/head> &lt;body>
&lt;h1>Welcome Finxters&lt;/h1> &lt;p>Example demonstrating How to generate HTML Files in Python&lt;/p> &lt;/body>
&lt;/html>''') # Saving the data into the HTML file
file_html.close()</pre>
<p><strong>Output:</strong> Here’s how the <code>demo.html</code> file looks like. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;html>
&lt;head>
&lt;title>HTML File&lt;/title>
&lt;/head> &lt;body>
&lt;h1>Welcome Finxters&lt;/h1> &lt;p>Example demonstrating How to generate HTML Files in Python&lt;/p> &lt;/body>
&lt;/html></pre>
<p>When you open it in the browser, it looks like this:</p>
<div class="wp-block-image is-style-default">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="1005" height="158" src="https://blog.finxter.com/wp-content/uploads/2022/04/generate_html_python_pic1.jpg" alt="" class="wp-image-310554" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/generate_html_python_pic1.jpg 1005w, https://blog.finxter.com/wp-content/uplo...300x47.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x121.jpg 768w" sizes="(max-width: 1005px) 100vw, 1005px" /></figure>
</div>
<h2>Method 1: Using the Airium Library</h2>
<p class="has-global-color-8-background-color has-background"><a rel="noreferrer noopener" href="https://pypi.org/project/airium/" data-type="URL" data-id="https://pypi.org/project/airium/" target="_blank">Airium</a> is a bidirectional HTML-Python translator that uses the DOM structure and is represented by the Python indentation with context managers. </p>
<p>We need to install the <code>airium</code> module using the Python package installer by running the following code in the terminal: </p>
<pre class="wp-block-preformatted"><code>pip install airium == 0.2.5</code></pre>
<p>The biggest advantage of using the Airium library in Python is that it also has a reverse translator. This translator helps to build the Python code out of the HTML string.</p>
<p><strong>Example: </strong>The following example demonstrates how we can generate HTML docs using Airium.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Importing the airium library
from airium import Airium a = Airium() # Generating HTML file
a('&lt;!DOCTYPE html>') with a.html(lang="pl"): with a.head(): a.meta(charset="utf-8") a.title(_t="Example: How to use Airium library") with a.body(): with a.h1(id="id23345225", kclass='main_header'): a("Hello Finxters") # Casting the file to a string to extract the value
html = str(a) # Casting the file to UTF-8 encoded bytes:
html_bytes = bytes(a) print(html)</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html lang="pl"> &lt;head> &lt;meta charset="utf-8" /> &lt;title>Example: How to use Airium library&lt;/title> &lt;/head> &lt;body> &lt;h1 id="id23345225" kclass="main_header"> Hello Finxters &lt;/h1> &lt;/body>
&lt;/html></pre>
<p>You can also store this document as a file using the following code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">with open('file.html', 'wb') as f: f.write(bytes(html, encoding='utf8'))</pre>
<h2>Method 2 – Using Yattag Library</h2>
<p class="has-global-color-8-background-color has-background"><a rel="noreferrer noopener" href="https://www.yattag.org/" data-type="URL" data-id="https://www.yattag.org/" target="_blank">Yattag</a> is a Python library used to generate HTML or XML documents in a Pythonic way. If we are using the Yattag library, we don’t have to use the closing tag in HTML. It considers all the templates as the piece of code in Python. We can even render the HTML forms easily with default values and error messages. </p>
<p>Before we dive into the solution, let us have a quick look at a few basics.</p>
<p><strong>How does the <code>yattag.Doc</code> class work</strong>?</p>
<p><code>Yattag.Doc</code> works similarly to the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-join/" data-type="post" data-id="26062" target="_blank"><code>join()</code></a> method of the string. When we create a Doc instance, it uses its method to append the content to it, like the <code>text()</code> method is used to append the text, whereas the <code>tag()</code> method appends the HTML tag. Lastly, the <code>getvalue()</code> method is used to return the whole HTML content as a large string. </p>
<p><strong>What is the <code>tag()</code> method</strong>?</p>
<p>In Python, a <code>tag()</code> method is an object that is used inside a <code>with</code> statement. It is used to return a context manager. The context managers have <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-__enter__-magic-method/" data-type="post" data-id="140907" target="_blank">__enter__()</a></code> and <code><a href="https://blog.finxter.com/python-__exit__-magic-method/" data-type="post" data-id="140981" target="_blank" rel="noreferrer noopener">__exit__()</a></code> methods where the <code>__enter__</code> method is called at the starting of the with block and the <code>__exit__</code> method is called when leaving the with block. </p>
<p>The line <code>tag('h1')</code> is used to create a <code>&lt;h1></code> tag.</p>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Importing the Yattag library
from yattag import Doc doc, tag, text = Doc().tagtext() with tag('html'): with tag('body'): with tag('p', id = 'main'): text('We can write any text here') with tag('a', href = '/my-link'): text('We can insert any link here') result = doc.getvalue()
print(result)</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;html>&lt;body>&lt;p id="main">We can write any text here&lt;/p>&lt;a href="/my-link">We can insert any link here&lt;/a>&lt;/body>&lt;/html></pre>
<p>It is easier and more readable to generate dynamic HTML documents with the Yattag library than to write static HTML docs. </p>
<p>However, most of the time, when you are generating HTML documents, most of the tag nodes will contain only text. Hence, we can use the following line method to write these more concisely.</p>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">doc, tag, text, line = Doc().ttl()
with tag('ul', id = 'To-dos'): line('li', 'Clean up the dishes', kclass = "priority") line('li', 'Call for appointment') line('li', 'Complete the paper')</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;ul id = 'To-dos'> &lt;li class = "priority"> Clean up the dishes &lt;/li> &lt;li> Call for appointment &lt;/li> &lt;li> Complete the paper &lt;/li>
&lt;/ul></pre>
<h2>Method 3: Using xml.etree </h2>
<p class="has-global-color-8-background-color has-background">We can use the <code>XML.etree</code> package to generate some low-level HTML documents in Python. The <code>XML.etree</code> is a standard python package, and we need to import it into the program before utilizing it.</p>
<p>XML follows the hierarchical data format and is usually represented in the form of an element tree. The element tree also has two classes for this purpose. </p>
<ul>
<li>The first one is the <code>ElementTree</code> that represents the whole XML document as a tree and interacts with the whole document (reading and writing to and from the files.) </li>
<li>The second class is the <code>Element</code> that represents a single node in this tree that interacts with a single XML element and its sub-elements.</li>
</ul>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Importing the XML package and the sys module
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 Finxters. This article explains how to generate HTML documents in Python." # Here, the code checks the Python version.
if sys.version_info &lt; (3, 0, 0): # If the Python version is less than 2.0 ET.ElementTree(html).write(sys.stdout, encoding='utf-8', method='html')
else: # For versions Python 3 and above ET.ElementTree(html).write(sys.stdout, encoding='unicode', method='html')</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;html>&lt;body>&lt;div class="foo">&lt;span class="bar">Hello Finxters. This article explains how to generate HTML documents in Python.&lt;/span>&lt;/div>&lt;/body>&lt;/html></pre>
<h2>Conclusion</h2>
<p>That’s all about generating HTML documents in Python. I hope you found this article helpful. Please stay tuned and <strong><a href="https://blog.finxter.com/" target="_blank" rel="noreferrer noopener">subscribe</a></strong> for more such interesting articles. Happy learning!</p>
<p class="has-text-align-center has-global-color-8-background-color has-background" style="font-size:16px">Authors:&nbsp;<strong>Rashi Agarwal</strong>&nbsp;and&nbsp;<strong>Shubham Sayon</strong></p>
<p><strong>Recommended Read: <a href="https://blog.finxter.com/how-to-get-an-html-page-from-a-url-in-python/" target="_blank" rel="noreferrer noopener">How to Get an HTML Page from a URL in Python?</a></strong></p>
<hr class="wp-block-separator has-css-opacity"/>
<p class="has-text-align-center"><a href="https://academy.finxter.com/university/web-scraping-with-beautifulsoup/"><strong>Web Scraping with BeautifulSoup</strong></a></p>
<div class="wp-block-image is-style-default">
<figure class="aligncenter is-resized"><a href="https://academy.finxter.com/university/web-scraping-with-beautifulsoup/"><img decoding="async" loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/03/image-105.png" alt="" class="wp-image-238589" width="485" height="191" srcset="https://blog.finxter.com/wp-content/uploads/2022/03/image-105.png 928w, https://blog.finxter.com/wp-content/uplo...00x119.png 300w, https://blog.finxter.com/wp-content/uplo...68x304.png 768w" sizes="(max-width: 485px) 100vw, 485px" /></a></figure>
</div>
<p>One of the most sought-after skills on Fiverr and Upwork is&nbsp;<strong>web scraping&nbsp;</strong>.</p>
<p>Make no mistake:&nbsp;<em><strong>extracting data programmatically from web sites&nbsp;</strong></em>is a critical life-skill in today’s world that’s shaped by the web and remote work.</p>
<p>This course teaches you the ins and outs of&nbsp;<em><strong>Python’s BeautifulSoup library&nbsp;</strong></em>for web scraping.</p>
</div>


https://www.sickgaming.net/blog/2022/12/...easy-ways/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016