Python的等价物是PHP的strip_tags函数吗?

23

1
请查看此链接:http://code.activestate.com/recipes/52281/ - Gagandeep Singh
谢谢Gagandeep。您可以发布一个答案,我会点赞它。 - Viet
8个回答

41

Python标准库中没有这样的功能。这是因为Python是一种通用语言,而PHP最初是面向Web的语言。

尽管如此,您有三种解决方案:

  • 如果您很匆忙:可以自己编写。 re.sub(r'<[^>]*?>', '', value) 可以是一种快速且简单的解决方案。
  • 使用第三方库(推荐,因为更可靠):beautiful soup 是一个非常好的库,无需安装,只需要复制 lib 目录并导入。 这里有一个带有 beautiful soup 的完整教程
  • 使用框架。 大多数Web Python开发人员不会从头开始编码,他们使用框架,例如django ,该框架可以自动处理这些内容。 这里有一个带有 django 的完整教程

@Hank 抱歉造成任何困惑。不幸的是,这不再是一个好方法。 - Andrew Scott Evans

15

使用BeautifulSoup

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(htmltext)
''.join([e for e in soup.recursiveChildGenerator() if isinstance(e,unicode)])

你可能需要让他知道这是一个第三方库。 - Bite code

9
from bleach import clean
print clean("<strong>My Text</strong>", tags=[], strip=True, strip_comments=True)

2

由于Python更多是一种通用的脚本语言而不是Web开发语言,因此你不会在Python内置函数中找到许多与PHP HTML函数相对应的内置Python函数。对于HTML处理,通常建议使用BeautifulSoup


1

这个有一个活动状态的配方,

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

这是一段旧代码,所以你需要根据评论中的建议将 SGML 解析器更改为 HTML 解析器。

以下是修改后的代码:

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

1

我使用HTMLParser类为Python 3构建了一个程序。它比PHP的更冗长。我称之为HTMLCleaner类,你可以在这里找到源代码,也可以在这里找到示例。


0

实际上,我用你建议的相同查询在谷歌上搜索过了,但那些结果并没有让我满意。 - Viet

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接