Minimize HTML using Python

I'm going to share a simply Python script that will minimize your HTML file using the BeautifulSoup library.

Minimize HTML using Python
Photo by Nathan da Silva / Unsplash

I'm going to share a simply Python script that will minimize your HTML file using the BeautifulSoup library.

from bs4 import BeautifulSoup

# read the HTML file
with open('src.html', 'r') as f:
    html = f.read()

# parse the HTML using BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')

# remove whitespace
for element in soup.recursiveChildGenerator():
    if hasattr(element, 'strip') and callable(element.strip):
        element.strip()

# minimize the HTML
minimized_html = str(soup).replace('\n', '').replace('\t', '')

# write the minimized HTML to a file
with open('dist.html', 'w') as f:
    f.write(minimized_html)

You should ensure to change the file name of the source HTML file on line four and the distribution HTML file on line 19.

You can run this script by saving it to a file as minimize_html.py and then running python minimize_html.py in your terminal.