- Author:
- henriklied
- Posted:
- April 27, 2007
- Language:
- Python
- Version:
- .96
- Score:
- 10 (after 10 ratings)
Originally posted by akaihola as snippet #169. I just redid it as a filter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from BeautifulSoup import BeautifulSoup, Comment
register = template.Library()
def sanitize_html(value):
valid_tags = 'p i strong b u a h1 h2 h3 pre br img'.split()
valid_attrs = 'href src'.split()
soup = BeautifulSoup(value)
for comment in soup.findAll(
text=lambda text: isinstance(text, Comment)):
comment.extract()
for tag in soup.findAll(True):
if tag.name not in valid_tags:
tag.hidden = True
tag.attrs = [(attr, val) for attr, val in tag.attrs
if attr in valid_attrs]
return soup.renderContents().decode('utf8').replace('javascript:', '')
register.filter('santize', sanitize_html)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Might want to try changing the 'javascript' regex in the second-to-last line with this regex instead:
(all on one line, of course)
It's long and unwieldy but I think it catches the above issues, and then some (embedded entity tabs/linebreaks, for example).
#
Beware also of the typo on the last line. Author presumably meant to write "sanitize" instead of "santize".
#
Please login first before commenting.