Created
November 18, 2011 20:07
-
-
Save stephenmcd/1377600 to your computer and use it in GitHub Desktop.
HTMLParser that closes open tags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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