Format HTML with indentation for improved readability and debugging.
Code
Utilitiesfrom html.parser import HTMLParser
import re
class Prettifier(HTMLParser):
def __init__(self, indent_size):
super().__init__()
self.indent_size = indent_size
self.level = 0
self.result = []
def handle_starttag(self, tag, attrs):
attrs_str = ''.join(f' {k}="{v}"' for k, v in attrs) if attrs else ''
self.result.append(' ' * (self.level * self.indent_size) + f'<{tag}{attrs_str}>')
self.level += 1
def handle_endtag(self, tag):
self.level -= 1
self.result.append(' ' * (self.level * self.indent_size) + f'</{tag}>')
def handle_data(self, data):
text = data.strip()
if text:
self.result.append(' ' * (self.level * self.indent_size) + text)
p = Prettifier(indent)
p.feed(html)
return '\n'.join(p.result)Parameters
HTML string to format.
Number of spaces for indentation.
Server
More Python Snippets
Array Difference
Find elements in the first array that are not present in the second array.
Array Frequencies
Count how many times each value appears in an array and return a frequency map.
Array Head
Get the first n elements of an array.
Array Intersection
Find common elements that exist in both arrays.
Array Tail
Get the last n elements of an array.
Array Union
Combine two arrays and remove duplicates to produce a union.