Created
May 10, 2022 20:33
-
-
Save gabriel-russo/fa968bdbab2f7fed87b3c0eae3c39f72 to your computer and use it in GitHub Desktop.
Python generate a dynamic html file pretty printed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from re import sub | |
from lxml.html.soupparser import fromstring | |
from lxml.etree import tostring | |
html_str = """\ | |
<html lang="en-US"> | |
<head><meta charset="utf-8"><title>REGEX PYTHON</title></head> | |
<style> | |
body {display: flex;flex-direction: column;justify-content: center;align-items: center} | |
div {display: flex;flex-direction: column} | |
</style> | |
<body>""" | |
for i in range(1, 6): # Dinamic html with python example | |
html_str += "\n" | |
html_str += f"<h{i}> Dinamic html in python </h{i}>" | |
html_str += "</body></html>" | |
html_one_line = sub(r'(?<=>|})\s+(?=<|\{)?', r'', html_str) # Regex to remove all blank/new lines outside tags | |
# Output: | |
# <html lang="en-US"><head><meta charset="utf-8"><title>REGEX PYTHON</title></head><style>body {display: flex;flex-direction... | |
html_document = fromstring(html_one_line) | |
print(tostring(html_document, encoding='unicode', pretty_print=True)) | |
# Output: | |
# <html lang="en-US"> | |
# <head> | |
# <meta charset="utf-8"/> | |
# <title>REGEX PYTHON</title> | |
# </head> | |
# <style>body {display: flex;flex-direction: column;justify-content: center;align-items: center}div {display: flex;flex-direction: column}</style> | |
# <body> | |
# <h1>Dinamic html in python </h1> | |
# <h2>Dinamic html in python </h2> | |
# <h3>Dinamic html in python </h3> | |
# <h4>Dinamic html in python </h4> | |
# <h5>Dinamic html in python </h5> | |
# </body> | |
# </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment