Python: unescape special characters without splitting data

Viewed 711

I have made a simple HTML parser which is basically a direct copy from the docs. I am having trouble unescaping special characters without also splitting up data into multiple chunks.

Here is my code with a simple example:

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.data = []

    def handle_starttag(self, tag, attrs):
        #print (tag,attrs)
        pass

    def handle_endtag(self, tag):
        #print (tag)
        pass

    def handle_data(self, data):
        self.data.append(data)

    def handle_charref(self, ref):
        self.handle_entityref("#" + ref)

    def handle_entityref(self, ref):
        self.handle_data(self.unescape("&%s;" % ref))



n = "<strong>I &lt;3s U &amp; you luvz me</strong>"


parser = MyHTMLParser()
parser.feed(n)
parser.close()
data = parser.data
print(data)

The issue is that this returns 5 separate bits of data

['I ', u'<', '3s U ', u'&', ' you luvz me']

Where what I want is the single string:

['I <3s U & you luvz me']

Thanks JP

3 Answers
Related