Appengine Python Env에서 HTML 태그 제거 (Ruby 's Sanitize와 동일)
-
19-09-2019 - |
문제
HTML 태그를 제거하지만 텍스트 값을 유지하는 데 도움이되는 파이썬 모듈을 찾고 있습니다. 나는 전에 BeautifulSoup을 시도했지만이 간단한 작업을 수행하는 방법을 알 수 없었습니다. 나는 이것을 할 수있는 Python 모듈을 검색하려고 시도했지만 모두 Appengine에서 잘 작동하지 않는 다른 라이브러리에 의존하는 것 같습니다.
아래는 Ruby 's Sanitize Library의 샘플 코드이며 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'
귀하의 제안에 감사드립니다.
-이자형
해결책
>>> 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']
이것은 당신에게 (유니 코드) 문자열 목록을 제공합니다. 단일 문자열로 바꾸려면 사용하십시오. ''.join(thatlist)
.
다른 팁
별도의 리브를 사용하지 않으려면 표준 Django Utils를 가져올 수 있습니다. 예를 들어:
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 }}
BTW, 이것은 가장 빠른 방법 중 하나입니다.
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
#!/usr/bin/python
from xml.dom.minidom import parseString
def getText(el):
ret = ''
for child in el.childNodes:
if child.nodeType == 3:
ret += child.nodeValue
else:
ret += getText(child)
return ret
html = '<b>this is <a href="http://foo.com/">a link </a> and some bold text </b> followed by <img src="http://foo.com/bar.jpg" /> an image'
dom = parseString('<root>' + html + '</root>')
print getText(dom.documentElement)
인쇄물:
이것은 링크와 약간의 굵은 텍스트와 이미지가 이어집니다.
늦었지만.
jinja2.markup ()를 사용할 수 있습니다.
http://jinja.pocoo.org/docs/api/#jinja2.markup.striptags
from jinja2 import Markup
Markup("<div>About</div>").striptags()
u'About'
제휴하지 않습니다 StackOverflow