You can use htmlmin to minify your html:

import htmlmin

html = """
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body> 
<div class="container">
  <h2>Well</h2>
  <div class="well">Basic Well</div>
</div>
</body>
</html>
"""

minified = htmlmin.minify(html.decode("utf-8"), remove_empty_space=True)
print(minified)
Answer from user7161360 on Stack Overflow
🌐
PyPI
pypi.org › project › minify-html
minify-html
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Top answer
1 of 5
26

You can use htmlmin to minify your html:

import htmlmin

html = """
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body> 
<div class="container">
  <h2>Well</h2>
  <div class="well">Basic Well</div>
</div>
</body>
</html>
"""

minified = htmlmin.minify(html.decode("utf-8"), remove_empty_space=True)
print(minified)
2 of 5
12

htmlmin and html_slimmer are some simple html minifying tools for python. I have millions of html pages stored in my database and running htmlmin, I am able to reduce the page size between 5 and 50%. Neither of them do an optimal job at complete html minification (i.e. the font color #00000 can be reduced to #000), but it's a good start. I have a try/except block that runs htmlmin and then if that fails, html_slimmer because htmlmin seems to provide better compression, but it does not support non ascii characters.

Example Code:

import htmlmin
from slimmer import html_slimmer # or xhtml_slimmer, css_slimmer
try:
    html=htmlmin.minify(html, remove_comments=True, remove_empty_space=True)
except:
    html=html_slimmer( html.strip().replace('\n',' ').replace('\t',' ').replace('\r',' ')  )

Good Luck!

🌐
Readthedocs
htmlmin.readthedocs.io
htmlmin — htmlmin 0.1 documentation
Properly handles unclosed HTML5 tags. Optionally remove comments while marking some comments to keep. Simple function decorator to minify all function output. Simple WSGI middleware to minify web app output. Tested in both Python 2.7 and 3.2: Index ·
🌐
GitHub
github.com › adamchainz › django-minify-html
GitHub - adamchainz/django-minify-html: Use minify-html, the extremely fast HTML + JS + CSS minifier, with Django.
Use minify-html, the extremely fast HTML + JS + CSS minifier, with Django. Work smarter and faster with my book Boost Your Django DX which covers many ways to improve your development experience. Python 3.10 to 3.14 supported.
Starred by 158 users
Forked by 8 users
Languages   Python
🌐
Gentoo
packages.gentoo.org › packages › dev-python › minify-html
dev-python/minify-html – Gentoo Packages
Extremely fast and smart HTML + JS + CSS minifier · https://github.com/wilsonzlin/minify-html/
🌐
GeeksforGeeks
geeksforgeeks.org › python › minify-html-in-flask-using-flask-minify
Minify HTML in Flask using Flask-Minify - GeeksforGeeks
July 24, 2025 - Python3 · from flask import Flask from flask_minify import minify app = Flask(__name__) # initializing minify for html, js and cssless minify(app=app, html=True, js=True, cssless=True) Step 2: Adding route, output HTML with minified code.
🌐
Python
bugs.python.org › file12183 › minify.py
Python
#!/usr/bin/env python """A simple script to minify HTML. It may have bugs. It does not handle JavaScript or CSS; there are good programs available that do that.
🌐
GitHub
github.com › cobrateam › django-htmlmin
GitHub - cobrateam/django-htmlmin: HTML minifier for Python frameworks (not only Django, despite the name).
django-html is an HTML minifier for Python, with full support for HTML 5. It supports Django, Flask and many other Python web frameworks.
Starred by 544 users
Forked by 73 users
Languages   Python 55.4% | HTML 44.0% | Makefile 0.6%
🌐
GitHub
gist.github.com › waterrmalann › 7318e61de34341a3c3bf9964e144c547
Simple Python Utility to Minify HTML/CSS/JS! · GitHub
Simple Python Utility to Minify HTML/CSS/JS! GitHub Gist: instantly share code, notes, and snippets.
Find elsewhere
🌐
PyPI
pypi.org › project › minify-html › 0.4.5
minify-html · PyPI
An HTML minifier meticulously optimised for both speed and effectiveness written in Rust. Comes with native bindings to Node.js, Python, Java, and Ruby.
      » pip install minify-html
    
Published   Apr 06, 2021
Version   0.4.5
🌐
PyPI
pypi.org › project › htmlmin
htmlmin · PyPI
A configurable HTML Minifier with safety features.
      » pip install htmlmin
    
Published   Dec 29, 2017
Version   0.1.12
🌐
Full Stack Python
fullstackpython.com › minification.html
Minification - Full Stack Python
Minification is the process of reducing the size of static content assets that need to be transferred from a web server to the web browser client. The goal of minification is to make webpages and web applications load faster, without changing ...
🌐
Toptal
toptal.com › developers › html-minifier › documentation › python
HTML Minifier API Code Example for Python | Toptal®
HTML Minifier · Check the example on how to use · Python to minify a HTML hardcoded string and output to stdout: import requests response = requests.post('https://www.toptal.com/developers/html-minifier/api/raw', data=dict(input='<input type="text" />')).text print("{}".format(response)) Install ·
🌐
PyTutorial
pytutorial.com › minify-html-python
PyTutorial | How to Minify or Compress HTML in Python
February 19, 2020 - The code below will minify a simple ... class="toc2"> <a href="#1"><span class="number">1.</span> Method 1: turn a List to a Tuple using tuple() built-in function</a> </li> <li class="toc2"> <a href="#2"><span class="number">2.</span> ...
🌐
PyPI
pypi.org › project › django-minify-html
django-minify-html · PyPI
Use minify-html, the extremely fast HTML + JS + CSS minifier, with Django. Work smarter and faster with my book Boost Your Django DX which covers many ways to improve your development experience. Python 3.9 to 3.14 supported.
      » pip install django-minify-html
    
Published   Oct 27, 2025
Version   1.14.0
🌐
GitHub
github.com › juancarlospaco › css-html-js-minify
GitHub - juancarlospaco/css-html-js-minify: StandAlone Async cross-platform Minifier for the Web.
css-html-js-minify.py --help usage: css-html-js-minify.py [-h] [--version] [--wrap] [--prefix PREFIX] [--timestamp] [--quiet] [--hash] [--zipy] [--sort] [--comments] [--overwrite] [--after AFTER] [--before BEFORE] [--watch] [--multiple] [--beep] fullpath CSS-HTML-JS-Minify. StandAlone Async cross-platform Unicode-ready Python3-ready Minifier for the Web.
Starred by 215 users
Forked by 20 users
Languages   Python
🌐
Aspose
products.aspose.com › aspose.words › python via .net › compress › compress html
The code to compress HTML in Python
Make large HTML files smaller without loss of quality. Delete unnecessary and unused data. Shrink the size of a HTML file in code. The Python library provides developers with an integrated API to optimize HTML content.
🌐
Quora
quora.com › What-are-some-good-Python-libraries-for-minimizing-HTML
What are some good Python libraries for minimizing HTML? - Quora
Answer (1 of 2): AFAIK, there aren't any popular, production ready python HTML minifiers. This is for a good reason: HTML is difficult to minify reliably; often the overhead of minifying outweighs the performance gain. Unless you're serving a positively huge amount of HTML which can't be optimiz...
🌐
Reddit
reddit.com › r/python › please break my html minifier
r/Python on Reddit: Please break my HTML minifier
December 21, 2022 -

So I recently saw this post here where this guy got absolutely wrecked for posting his shitty code here, and not gonna lie, that was pretty funny.

So here is my turn!

Since the most popular Python lib for minifying HTML (htmlmin) is way too slow, I decided to make my own and honestly I'm surprised how short it is. It can't be that simple right? It is also about 10x faster than htmlmin. I challenge you to break this code to produce incorrect HTML:

from html.parser import HTMLParser
import rjsmin
import rcssmin


class MinifyHTMLParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.minified_html = ""

    def handle_decl(self, decl: str) -> None:
        self.minified_html += f"<!{decl}>"

    def unknown_decl(self, data: str) -> None:
        self.minified_html += f"<!{data}>"

    def handle_pi(self, data):
        self.minified_html += f"<?{data}>"

    def handle_startendtag(self, tag, attrs):
        self.add_tag(tag, attrs, "/>")

    def handle_entityref(self, name):
        self.minified_html += f"&{name};"

    def handle_charref(self, name):
        self.minified_html += f"&#x{name};"

    def handle_starttag(self, tag, attrs):
        self.add_tag(tag, attrs, ">")

    # TODO Rename this here and in `handle_startendtag` and `handle_starttag`
    def add_tag(self, tag, attrs, end_tag):
        self.minified_html += f"<{tag}"
        for attr in attrs:
            self.minified_html += f' {attr[0]}'
            if attr[1] is not None:
                self.minified_html += f'="{attr[1]}"'
        self.minified_html += end_tag

    def handle_endtag(self, tag):
        self.minified_html += f"</{tag}>"

    def handle_data(self, data):
        if self.lasttag == "style":
            self.minified_html += minify_css(data).strip()
        elif self.lasttag == "script":
            self.minified_html += minify_js(data).strip()
        elif self.lasttag in ["textarea", "pre", "code"]:
            self.minified_html += data
        else:
            self.minified_html += data.strip()

parser = MinifyHTMLParser()
parser.feed(html_text)
return parser.minified_html
🌐
Educative
educative.io › answers › how-to-minify-html-in-flask-using-flask-minify
How to minify HTML in Flask using Flask-Minify
from flask import Flask from flask_minify import minify, decorators app = Flask(__name__) minify(app=app, passive=True) @app.route('/') @decorators.minify(html=True, js=True, cssless=True) def home(): return """ <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h2>This is a Heading</h2> <p>This is a paragraph.</p> </body> </html> ""