删除AppEngine Python Env中的HTML标记(相当于Ruby的Sanitize)

2024-04-19 23:46:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个python模块,它将帮助我摆脱HTML标记,但保留文本值。我以前试过beauthulsoup,但我不知道怎么做这个简单的任务。我试着搜索可以做到这一点的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'

谢谢你的建议。在

-电子


Tags: 模块代码标记文本comhttp示例foo
3条回答

使用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
>>> 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)。在

如果不想使用单独的lib,那么可以导入标准的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模板中,所以您不需要其他任何东西,只需使用filter,如下所示:

^{pr2}$

顺便说一句,这是最快的方法之一。在

相关问题 更多 >