Search code examples
pythondjangohtml-parser

django remove tags from string python


I want to remove all html tags except from my string with python i use this:

from HTMLParser import HTMLParser   

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

But this remove all my html tags.


Solution

  • If I understand it right, you want to strip html tags, but to keep some specific ones ? If that's the case - then just keep monitoring the start/end tags, and process them if needed. Example:

    MY_TAGS = ["tag1", "tag2"]
    
    MLStripper(HTMLParser):
        def __init__(self):
            self.reset()
            self.fed = []
        def handle_data(self, d):
            self.fed.append(d)
        def get_data(self):
            return ''.join(self.fed)
    
        def handle_starttag(self, tag, attrs):
            if tag in MY_TAGS:
                self.fed.append("<%s>" % tag) # tag is only string, no < or >.
        def handle_endtag(self, tag):
            if tag in MY_TAGS:
                self.fed.append("</%s>" % tag)