Python's equivalent to PHP's strip_tags?

后端 未结 7 1330
情歌与酒
情歌与酒 2020-12-15 18:26

Python\'s equivalent to PHP\'s strip_tags?

http://php.net/manual/en/function.strip-tags.php

相关标签:
7条回答
  • 2020-12-15 18:53
    from bleach import clean
    print clean("<strong>My Text</strong>", tags=[], strip=True, strip_comments=True)
    
    0 讨论(0)
  • 2020-12-15 18:53

    Python doesn't have one built-in, but there are an ungodly number of implementations.

    0 讨论(0)
  • 2020-12-15 18:53

    I built one for Python 3 using the HTMLParser class. It is more verbose than PHP's. I called it the HTMLCleaner class, and you can find the source here and you can find examples here.

    0 讨论(0)
  • 2020-12-15 19:03

    There is an active state recipe for this,

    http://code.activestate.com/recipes/52281/

    It's old code so you have to change sgml parser to HTMLparser as mentioned in the comments

    Here is the modified code,

    import HTMLParser, string
    
    class StrippingParser(HTMLParser.HTMLParser):
    
        # These are the HTML tags that we will leave intact
        valid_tags = ('b', 'a', 'i', 'br', 'p', 'img')
    
        from htmlentitydefs import entitydefs # replace entitydefs from sgmllib
    
        def __init__(self):
            HTMLParser.HTMLParser.__init__(self)
            self.result = ""
            self.endTagList = []
    
        def handle_data(self, data):
            if data:
                self.result = self.result + data
    
        def handle_charref(self, name):
            self.result = "%s&#%s;" % (self.result, name)
    
        def handle_entityref(self, name):
            if self.entitydefs.has_key(name): 
                x = ';'
            else:
                # this breaks unstandard entities that end with ';'
                x = ''
            self.result = "%s&%s%s" % (self.result, name, x)
    
        def handle_starttag(self, tag, attrs):
            """ Delete all tags except for legal ones """
            if tag in self.valid_tags:       
                self.result = self.result + '<' + tag
                for k, v in attrs:
                    if string.lower(k[0:2]) != 'on' and string.lower(v[0:10]) != 'javascript':
                        self.result = '%s %s="%s"' % (self.result, k, v)
                endTag = '</%s>' % tag
                self.endTagList.insert(0,endTag)    
                self.result = self.result + '>'
    
        def handle_endtag(self, tag):
            if tag in self.valid_tags:
                self.result = "%s</%s>" % (self.result, tag)
                remTag = '</%s>' % tag
                self.endTagList.remove(remTag)
    
        def cleanup(self):
            """ Append missing closing tags """
            for j in range(len(self.endTagList)):
                    self.result = self.result + self.endTagList[j]    
    
    
    def strip(s):
        """ Strip illegal HTML tags from string s """
        parser = StrippingParser()
        parser.feed(s)
        parser.close()
        parser.cleanup()
        return parser.result
    
    0 讨论(0)
  • 2020-12-15 19:09

    Using BeautifulSoup

    from BeautifulSoup import BeautifulSoup
    soup = BeautifulSoup(htmltext)
    ''.join([e for e in soup.recursiveChildGenerator() if isinstance(e,unicode)])
    
    0 讨论(0)
  • 2020-12-15 19:11

    There is no such thing in the Python standard library. It's because Python is a general purpose language while PHP started as a Web oriented language.

    Nevertheless, you have 3 solutions:

    • You are in a hurry: just make your own. re.sub(r'<[^>]*?>', '', value) can be a quick and dirty solution.
    • Use a third party library (recommended because more bullet proof) : beautiful soup is a really good one and there is nothing to install, just copy the lib dir and import. Full tuto with beautiful soup.
    • Use a framework. Most Web Python devs never code from scratch, they use a framework such as django that does automatically this stuff for you. Full tuto with django.
    0 讨论(0)
提交回复
热议问题