在AppEngine Python环境中去除HTML标签(相当于Ruby的Sanitize)

1 投票
5 回答
1505 浏览
提问于 2025-04-15 20:14

我在找一个Python模块,能帮我去掉HTML标签,但保留文本内容。我之前试过BeautifulSoup,但没搞明白怎么完成这个简单的任务。我还搜索过其他可以做到这一点的Python模块,但它们似乎都依赖于其他库,而这些库在AppEngine上运行得不好。

下面是Ruby的sanitize库中的一段示例代码,这就是我想在Python中实现的:

require 'rubygems'
require 'sanitize'

html = '<b><a href="http://foo.com/">foo</a></b><img src="http://foo.com/bar.jpg" />'

Sanitize.clean(html) # => 'foo'

谢谢你的建议。

-e

5 个回答

1

使用 lxml 库:

htmlstring = '<b><a href="http://foo.com/">foo</a></b><img src="http://foo.com/bar.jpg" />'

from lxml.html import fromstring

mySearchTree = fromstring(htmlstring)

for item in mySearchTree.cssselect('a'):
    print item.text
4

如果你不想使用额外的库,那么可以直接导入Django自带的工具。比如:

from django.utils.html import strip_tags
html = '<b><a href="http://foo.com/">foo</a></b><img src="http://foo.com/bar.jpg'
stripped = strip_tags(html)
print stripped 
# you got: foo

而且这些工具已经包含在Django的模板里,所以你不需要其他东西,只要使用过滤器,像这样:

{{ unsafehtml|striptags }}

顺便说一下,这也是最快的方法之一。

5
>>> import BeautifulSoup
>>> html = '<b><a href="http://foo.com/">foo</a></b><img src="http://foo.com/bar.jpg" />'
>>> bs = BeautifulSoup.BeautifulSoup(html)  
>>> bs.findAll(text=True)
[u'foo']

这段话告诉你,这个操作会给你一个包含多个(Unicode)字符串的列表。如果你想把这些字符串合成一个完整的字符串,可以用 ''.join(thatlist) 这个方法。

撰写回答