Create an account


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,114
» Latest member: gfhfhfh
» Forum threads: 21,709
» Forum posts: 22,575

Full Statistics

Online Users
There are currently 694 online users.
» 0 Member(s) | 689 Guest(s)
Applebot, Baidu, Bing, Google, Yandex

 
  [Tut] Python Generate HTML – 3 Easy Ways
Posted by: xSicKxBot - 12-31-2022, 02:12 PM - Forum: Python - No Replies

Python Generate HTML – 3 Easy Ways

5/5 – (4 votes)

? Problem Statement: How to generate HTML documents in Python?

One of the advantages of opting for Python 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.

Before we dive into the libraries, let us learn how we can actually write to an HTML file in Python.

How to Write to an HTML File in Python?


You can create and save HTML files with the help of a few simple steps:

  1. Use the open() file function to create the HTML file.
  2. Add input data in HTML format into the file with the help of the write() function.
  3. Finally, save and close the file.

Example:

# Creating the HTML file
file_html = open("demo.html", "w") # Adding the input data to the HTML file
file_html.write('''<html>
<head>
<title>HTML File</title>
</head> <body>
<h1>Welcome Finxters</h1> <p>Example demonstrating How to generate HTML Files in Python</p> </body>
</html>''') # Saving the data into the HTML file
file_html.close()

Output: Here’s how the demo.html file looks like. ?

<html>
<head>
<title>HTML File</title>
</head> <body>
<h1>Welcome Finxters</h1> <p>Example demonstrating How to generate HTML Files in Python</p> </body>
</html>

When you open it in the browser, it looks like this:


Method 1: Using the Airium Library


Airium is a bidirectional HTML-Python translator that uses the DOM structure and is represented by the Python indentation with context managers.

We need to install the airium module using the Python package installer by running the following code in the terminal:

pip install airium == 0.2.5

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.

Example: The following example demonstrates how we can generate HTML docs using Airium.

# Importing the airium library
from airium import Airium a = Airium() # Generating HTML file
a('<!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)

Output:

<!DOCTYPE html>
<html lang="pl"> <head> <meta charset="utf-8" /> <title>Example: How to use Airium library</title> </head> <body> <h1 id="id23345225" kclass="main_header"> Hello Finxters </h1> </body>
</html>

You can also store this document as a file using the following code:

with open('file.html', 'wb') as f: f.write(bytes(html, encoding='utf8'))

Method 2 – Using Yattag Library


Yattag 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.

Before we dive into the solution, let us have a quick look at a few basics.

How does the yattag.Doc class work?

Yattag.Doc works similarly to the join() method of the string. When we create a Doc instance, it uses its method to append the content to it, like the text() method is used to append the text, whereas the tag() method appends the HTML tag. Lastly, the getvalue() method is used to return the whole HTML content as a large string. 

What is the tag() method?

In Python, a tag() method is an object that is used inside a with statement. It is used to return a context manager. The context managers have __enter__() and __exit__() methods where the __enter__ method is called at the starting of the with block and the __exit__ method is called when leaving the with block.

The line tag('h1') is used to create a <h1> tag.

Example:

# 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)

Output:

<html><body><p id="main">We can write any text here</p><a href="/my-link">We can insert any link here</a></body></html>

It is easier and more readable to generate dynamic HTML documents with the Yattag library than to write static HTML docs. 

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.

Example:

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')

Output:

<ul id = 'To-dos'> <li class = "priority"> Clean up the dishes </li> <li> Call for appointment </li> <li> Complete the paper </li>
</ul>

Method 3: Using xml.etree


We can use the XML.etree package to generate some low-level HTML documents in Python. The XML.etree is a standard python package, and we need to import it into the program before utilizing it.

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.

  • The first one is the ElementTree that represents the whole XML document as a tree and interacts with the whole document (reading and writing to and from the files.)
  • The second class is the Element that represents a single node in this tree that interacts with a single XML element and its sub-elements.

Example:

# 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 < (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')

Output:

<html><body><div class="foo"><span class="bar">Hello Finxters. This article explains how to generate HTML documents in Python.</span></div></body></html>

Conclusion


That’s all about generating HTML documents in Python. I hope you found this article helpful. Please stay tuned and subscribe for more such interesting articles. Happy learning!

Authors: Rashi Agarwal and Shubham Sayon

Recommended Read: How to Get an HTML Page from a URL in Python?


Web Scraping with BeautifulSoup


One of the most sought-after skills on Fiverr and Upwork is web scraping .

Make no mistake: extracting data programmatically from web sites is a critical life-skill in today’s world that’s shaped by the web and remote work.

This course teaches you the ins and outs of Python’s BeautifulSoup library for web scraping.



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

Print this item

  (Free Game Key) Worms Revolution Gold Edition - Free GOG Game
Posted by: xSicKxBot - 12-31-2022, 02:12 PM - Forum: Deals or Specials - No Replies

Worms Revolution Gold Edition - Free GOG Game

How to grab Worms Revolution Gold Edition
- Go to the home page of https://www.gog.com/#giveaway
- Login and Register
- Go to the home page again
- Wait for 10 seconds then start searching for Worms Revolution Gold Edition
- on the home page look for "Deal of the Day" (above it there should be a banner)
- on the banner there is a button "Yes, and claim the game" click it
- Thats it


GOG Store link: https://www.gog.com/game/Worms_Revolution
Auto-claim link: https://www.gog.com/giveaway/claim

We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.

?GrabFreeGames.com ?Twitter ?Steam Curator ?Facebook[fb.me]?Discord[discord.gg]
❤️Support us: HumbleBundle Partner[www.humblebundle.com] Fanatical Affiliate[www.fanatical.com]


https://steamcommunity.com/groups/GrabFr...9255760179

Print this item

  (Indie Deal) Festive Giveaways, Disney Deals, Last Of Us coming to PC
Posted by: xSicKxBot - 12-31-2022, 02:12 PM - Forum: Deals or Specials - No Replies

Festive Giveaways, Disney Deals, Last Of Us coming to PC

Winter Sales Top Deals
[www.indiegala.com]
Don't forget you may get up to 3 extra BONUS games with each purchase. Read more here[www.indiegala.com].
[www.indiegala.com]
The Last of Us™ Part I coming to PC
[www.indiegala.com]
https://www.youtube.com/watch?v=LW5NwaUXgIA
Festive Giveaways
[www.indiegala.com]
https://www.youtube.com/watch?v=-fZVwrT4uaM


https://steamcommunity.com/groups/indieg...0198638354

Print this item

  PC - Potion Craft: Alchemist Simulator
Posted by: xSicKxBot - 12-31-2022, 02:12 PM - Forum: New Game Releases - No Replies

Potion Craft: Alchemist Simulator



Potion Craft is an alchemist simulator where you physically interact with your tools and ingredients to brew potions. You're in full control of the whole shop: invent new recipes, attract customers and experiment to your heart's content. Just remember: the whole town is counting on you.

Every day customers will come to your store looking for solutions to their problems. You will face consequences depending on what you decide to sell them. Attract guilds, befriend notable figures (or feud with them), gain riches and influence - and one day, you may even decide the fate of the whole town.

Publisher: niceplay games

Release Date: Dec 13, 2022




https://www.metacritic.com/game/pc/potio...-simulator

Print this item

  News - Elden Ring: Where To Get Great Glintstone Shard
Posted by: xSicKxBot - 12-31-2022, 02:12 PM - Forum: Lounge - No Replies

Elden Ring: Where To Get Great Glintstone Shard

Are you on a quest to obtain every Elden Ring spell? Well, if so, you'll need to make sure you get your hands on Great Glintstone Shard, even if it's not the most efficient spell to add to your arsenal. Getting it doesn't take too much effort, luckily, but we'll walk you through the necessary steps in this guide.

Great Glintstone Shard explained

Great Glintstone Shard is a sorcery that requires 16 Intelligence to cast. It fires a large projectile that can kill many smaller enemies in a single hit, but due to its high FP cost, it's rarely worth using it over something more efficient like Glintstone Pebble.

Great Glintstone Shard's item description reads:

Continue Reading at GameSpot

https://www.gamespot.com/articles/elden-...01-10abi2f

Print this item

  [Oracle Blog] JDK 16.0.1, 11.0.11, 8u291, and 7u301 Have Been Released!
Posted by: xSicKxBot - 12-30-2022, 03:59 AM - Forum: Java Language, JVM, and the JRE - No Replies

JDK 16.0.1, 11.0.11, 8u291, and 7u301 Have Been Released!

The Java SE 16.0.1, 11.0.11, 8u291, and 7u301 update releases are now available. You can download the latest JDK releases from the Java SE Downloads page. OpenJDK 16.0.1 is available on http://jdk.java.net/16/. New Features, Changes, and Notable Bug Fixes For information about the new features, chan...


https://blogs.oracle.com/java/post/jdk-1...n-released

Print this item

  (Indie Deal) Festive Giveaways, Disney Deals, Last Of Us coming to PC
Posted by: xSicKxBot - 12-30-2022, 03:59 AM - Forum: Deals or Specials - No Replies

Festive Giveaways, Disney Deals, Last Of Us coming to PC

Winter Sales Top Deals
[www.indiegala.com]
Don't forget you may get up to 3 extra BONUS games with each purchase. Read more here[www.indiegala.com].
[www.indiegala.com]
The Last of Us™ Part I coming to PC
[www.indiegala.com]
https://www.youtube.com/watch?v=LW5NwaUXgIA
Festive Giveaways
[www.indiegala.com]
https://www.youtube.com/watch?v=-fZVwrT4uaM


https://steamcommunity.com/groups/indieg...0198628635

Print this item

  (Free Game Key) Steam Replay Badge - 50XP
Posted by: xSicKxBot - 12-30-2022, 03:59 AM - Forum: Deals or Specials - No Replies

Steam Replay Badge - 50XP

Steam Replay Badge

50XP (maybe there is more, i cant figure it out)
https://store.steampowered.com/replay/
Visit the link above and see your steam stats and get a 50XP Badge

We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.

?GrabFreeGames.com ?Twitter ?Steam Curator ?Facebook[fb.me]?Discord[discord.gg]
❤️Support us: HumbleBundle Partner[www.humblebundle.com] Fanatical Affiliate[www.fanatical.com]


https://steamcommunity.com/groups/GrabFr...9253039518

Print this item

  PC - High on Life
Posted by: xSicKxBot - 12-30-2022, 03:59 AM - Forum: New Game Releases - No Replies

High on Life



Fresh out of high school with no job and no ambition, you've really got nothing going for you until an alien cartel that wants to get high off humanity invades Earth. Now, you and a team of charismatic talking guns must answer the hero's call and become the deadliest intergalactic bounty hunter the cosmos has ever seen.

Travel to various planets and locations across the cosmos, go up against the nefarious Garmantuous and his gang of goons, collect loot, meet unique characters, and more, in the latest comedy adventure from Justin Roiland!

Navigate dynamic and changing worlds that range from a jungle paradise, to a city built inside an asteroid, the hub of the cosmos.

Leverage the distinct skills of each gun to defeat a variety of diabolical alien enemies and track down Garmantuous.

Complete hunter challenges, meet weird, fun, and hilarious characters, collect an array of alien technology, and more!

Publisher: Squanch Games

Release Date: Dec 13, 2022




https://www.metacritic.com/game/pc/high-on-life

Print this item

  [Oracle Blog] The Secret Weapon of Top Performing Companies? It’s All in Who You Ask.
Posted by: xSicKxBot - 12-29-2022, 09:18 AM - Forum: Java Language, JVM, and the JRE - No Replies

The Secret Weapon of Top Performing Companies? It’s All in Who You Ask.

William Blake once said, “What is now proved was once only imagined.” Java has been the platform of choice for millions of developers over the past 25 years to take what’s imagined and make it real. In his new book, “Ask Your Developer: How to harness the power of software development to win the 21s...


https://blogs.oracle.com/java/post/the-s...ho-you-ask

Print this item

 
Latest Threads
(Free Game Key) [GOG] Sil...
Last Post: xSicKxBot
1 hour ago
News - $2.50 Steam Sale H...
Last Post: xSicKxBot
1 hour ago
Forza Horizon 5 Game Save...
Last Post: poxah56770
11 hours ago
(Xbox One) Vantage - Mod ...
Last Post: levihaxk
Today, 03:59 AM
News - Christopher Nolan’...
Last Post: xSicKxBot
Today, 03:31 AM
News - GameStop Is Not Hu...
Last Post: xSicKxBot
Yesterday, 11:06 AM
News - Subnautica 2’s Leg...
Last Post: xSicKxBot
07-05-2026, 06:45 PM
Redacted T6 Nightly Offli...
Last Post: Ngixk0
07-05-2026, 03:21 PM
News - Sony To End PlaySt...
Last Post: xSicKxBot
07-05-2026, 02:23 AM
Black Ops (BO1, T5) DLC's...
Last Post: BrookesBot
07-04-2026, 06:29 PM

Forum software by © MyBB Theme © iAndrew 2016