Skip to content

Instantly share code, notes, and snippets.

@stephenmcd
Created November 18, 2011 20:07
Show Gist options
  • Save stephenmcd/1377600 to your computer and use it in GitHub Desktop.
Save stephenmcd/1377600 to your computer and use it in GitHub Desktop.
HTMLParser that closes open tags
class TagCloser(HTMLParser):
"""
HTMLParser that closes open tags. Call close_tags with a HTML
string arg which returns it with any required closing tags
appended.
"""
def __init__(self):
HTMLParser.__init__(self)
self.tags = []
def handle_starttag(self, tag, attrs):
self.tags.insert(0, tag)
def handle_endtag(self, tag):
try:
self.tags.remove(tag)
except ValueError:
pass
def close_tags(self, html)
self.feed(html)
return html + "".join(["</%s>" % tag for tag in self.tags])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment