How to minify html or css files for improving web site speed using python ?

Published: November 25, 2022

Updated: November 25, 2022

Tags: Python; HTML; CSS; Minify;

DMCA.com Protection Status

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 htmlmin

html_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 htmlmin

f = 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 htmlmin
import re

f = 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.