Python 相当于 PHP 的 strip_tags?
问问题
12780 次
7 回答
39
Python 标准库中没有这样的东西。这是因为 Python 是一种通用语言,而 PHP 最初是一种面向 Web 的语言。
不过,您有 3 个解决方案:
- 你很着急:自己做。
re.sub(r'<[^>]*?>', '', value)
可能是一个快速而肮脏的解决方案。 - 使用第三方库(推荐,因为更防弹):beautiful soup是一个非常好的库,无需安装,只需复制 lib 目录并导入。完整的tuto配上漂亮的汤。
- 使用框架。大多数 Web Python 开发人员从不从头开始编写代码,他们使用诸如django之类的框架来自动为您完成这些工作。django 的完整教程。
于 2010-02-19T11:40:07.917 回答
15
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(htmltext)
''.join([e for e in soup.recursiveChildGenerator() if isinstance(e,unicode)])
于 2010-02-19T11:41:48.567 回答
9
from bleach import clean
print clean("<strong>My Text</strong>", tags=[], strip=True, strip_comments=True)
于 2013-10-11T16:47:46.613 回答
2
由于 Python 更像是一种通用脚本语言,而不是一种 Web 开发语言,因此您不会找到许多用于内置 PHP HTML 函数的内置 Python 等价物。对于 HTML 处理,一般推荐使用BeautifulSoup 。
于 2010-02-19T11:44:28.430 回答
1
Python 没有内置的,但有大量的实现。
于 2010-02-19T11:40:58.740 回答
1
我使用 HTMLParser 类为 Python 3 构建了一个。它比 PHP 更冗长。我将其称为 HTMLCleaner 类,您可以在此处找到源代码,也可以在此处找到示例。
于 2011-11-15T04:46:09.483 回答
1
为此有一个活动状态配方,
http://code.activestate.com/recipes/52281/
这是旧代码,因此您必须将 sgml 解析器更改为 HTMLparser,如评论中所述
这是修改后的代码,
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
于 2012-09-11T03:51:57.537 回答