Examples of how to minify html or css files for improving web site speed using python:
Minify html using htmlmin
A solution is to use the python module htmlmin that can be installed using pip:
pip install htmlmin
or conda-forge
conda install -c conda-forge htmlmin
Then to minify a html text:
import htmlminhtml_txt = '''<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>'''
just do
html_minified = htmlmin.minify(html_txt)print(html_minified)
gives here
<!DOCTYPE html><html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>
Note that it can be used with a css file as well:
css_txt = '''body {color: blue;}h1 {color: green;}'''
Minify css_txt
css_minified = htmlmin.minify(css_txt)print(css_minified)
gives
body { color: blue; } h1 { color: green; }
Write your own python code
Another solution is to try to create your own code to minify your css or html files. For example by doing
css_txt = '''body {color: blue;}h1 {color: green;}'''css_minified = ''.join( [line.strip() for line in css_txt] )css_minified
gives
body{color:blue;}h1{color:green;}
Create a min css or html file
To open and minify content from a html file
import htmlminf = open("test.html", "r")html_minified = htmlmin.minify(f.read())print(html_minified)f.close()
However note that here html_minified string has some control characters (\n \t \r):
<!DOCTYPE html><html> <head><style>body{color:blue;}h1{color:green;}</style></head> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>
To remove them, a solution is to do
import htmlminimport ref = open("test.html", "r")html_minified = htmlmin.minify(f.read())print(html_minified)regex = re.compile(r'[\n\r\t]')html_minified = regex.sub(" ", html_minified)print(html_minified)f.close()
gives
<!DOCTYPE html><html> <head><style> body{color:blue;}h1{color:green;} </style></head> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>
Create a new html file (called "test.min.html")
f = open("test.min.html", "x")f.write(html_minified)f.close()
Online Tools
There are several online tools to minify html or css files that can be used for comparison. I used for example: Online CSS Minifier Tool and Compressor, with Fast and Simple API Access
Other online tools: HTML Minifier or CSS Minify
Unminify
Note: To unminify css or html, there are also online tools such as unminify or css-html-prettify 2.5.5.
Related posts
| Links | Tags |
|---|---|
| How to remove string control characters (\n \t \r) in python | Python, Regular Expressions |
| How to check if a character from a string is a letter, a number, a special character or a whitespace in python ? | Python; special-character |
| How to remove leading spaces in a string with python ? | Python; Spaces |
