473,788 Members | 2,825 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HTML cleaner?

Is there a HTML clean/tidy library or module written in pure python? I
found mxTidy, but it's a interface to command-line tool.

What I'm searching is something that will accept a list of allowed tags
and/or attributes and strip the rest from HTML string.

Jul 19 '05 #1
7 2829
Probably you're looking for Beautiful Soup:
http://www.crummy.com/software/BeautifulSoup/

George

Jul 19 '05 #2
I *just* wrote something that does this. It uses the htmldata module -
you can find that using pypi. It only allows a specific set of html
tags and attempts to close tags not closed. :

from htmldata import tagextract, tagjoin
allowed_tags = ['br', 'b', 'strong', 'em', 'i', 'u', 'tt', 'a', 'big',
'small',
'h2', 'h3', 'h4', 'strike', 'sub', 'sup', 'samp', 's',
'code', 'ins',
'br/',
]
def htmlfilter(inte xt, allowed_tags=al lowed_tags):
"""Given a text entry as input, check it only contains allowed html.

It returns the text with banned html removed.
Uses two functiosn from htmldata :
from htmldata import tagextract, tagjoin
allowed_tags is the list of tags that are allowed.
"""
html = tagextract(inte xt) #
out_html = []
skip = None
unclosed = []
for entry in html:
if isinstance(entr y, basestring):
if skip is not None:
continue
out_html.append (entry)
else:
tag = entry[0]
if skip is not None:
if tag.startswith( '/') and tag[1:] == skip:
skip = None
continue
otag = tag
if tag.startswith( '/'):
otag = tag[1:]
if otag in allowed_tags:
if tag.startswith( '/'):
if otag in unclosed:
unlclosed.remov e(otag)
else: # bad html
continue
elif tag not in ['br', '/br', 'hr', '/hr', 'img',
'/img']: # XXXX hardwired - what if we need to add to this ?
unclosed.append (tag)
out_html.append (entry)
continue
if not tag.startswith( '/'):
skip = tag
for tag in unclosed:
out_html.append (('/%s' % (tag,), {})) # close any unclosed
tags
return tagjoin(out_htm l)
###############

I've used it to allow a few html tags to appear in my guestbook
entries. It's not very sophisticated because complex tags like 'div'
and tables aren't allowed.

Best regards,

Fuzzy
http://www.voidspace.org.uk/python

Jul 19 '05 #3
Ivan Voras wrote:
Is there a HTML clean/tidy library or module written in pure python? I
found mxTidy, but it's a interface to command-line tool.
Not true: mxTidy integrates tidy as C lib. It's not an interface
to the command line tool.
What I'm searching is something that will accept a list of allowed tags
and/or attributes and strip the rest from HTML string.


--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source (#1, Apr 25 2005)
Python/Zope Consulting and Support ... http://www.egenix.com/
mxODBC.Zope.Dat abase.Adapter ... http://zope.egenix.com/
mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/

_______________ _______________ _______________ _______________ ____________

::: Try mxODBC.Zope.DA for Windows,Linux,S olaris,FreeBSD for free ! ::::
Jul 19 '05 #4
Ivan Voras wrote:
Is there a HTML clean/tidy library or module written in pure python? I
found mxTidy, but it's a interface to command-line tool.

What I'm searching is something that will accept a list of allowed tags
and/or attributes and strip the rest from HTML string.


Here's a module I wrote to do something along the lines of what you
want: <http://ecritters.biz/limithtml.py>. Unfortunately, it requires
the HTML to be relatively well-formed (e.g. it doesn't like things like
"<i><b>foo</i></b>"), so I feed the HTML into uTidyLib (another
interface to HTML Tidy) first. I'm not sure why you don't want to use
Tidy, but if you do change your mind, you should be able to use my
module alongside Tidy to limit the HTML elements and attributes which
will be accepted.
Jul 19 '05 #5
M.-A. Lemburg wrote:
Not true: mxTidy integrates tidy as C lib. It's not an interface
to the command line tool.


Thanks, I'll look at it again!
Jul 19 '05 #6
Ivan Voras wrote:
M.-A. Lemburg wrote:
Not true: mxTidy integrates tidy as C lib. It's not an interface
to the command line tool.


Thanks, I'll look at it again!


Another option might be the HTML parser (libxml2.htmlRe adMemory()) from
libxml2 (http://www.xmlsoft.org)

Bye,
Walter Dörwald
Jul 19 '05 #7
On Sunday 24 April 2005 06:25 pm, Ivan Voras wrote:
Is there a HTML clean/tidy library or module written in pure python? I
found mxTidy, but it's a interface to command-line tool.

What I'm searching is something that will accept a list of allowed tags
and/or attributes and strip the rest from HTML string.


I'm using stripogram for this. It uses a whitelist approach, where you
tell it what tags to accept. It also has a function for getting text only.

http://www.zope.org/Members/chrisw/StripOGram/

It's very useful in Zope, but is actually an independent pure-python
module (you don't need Zope to use it). Also very small.

--
Terry Hancock ( hancock at anansispacework s.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2453
by: Leif K-Brooks | last post by:
I'm writing a site with mod_python which will have, among other things, forums. I want to allow users to use some HTML (<em>, <strong>, <p>, etc.) on the forums, but I don't want to allow bad elements and attributes (onclick, <script>, etc.). I would also like to do basic validation (no overlapping elements like <strong><em>foo</em></strong>, no missing end tags). I'm not asking anyone to write a script for me, but does anyone have general...
20
7358
by: Al Moritz | last post by:
Hi all, I was always told that the conversion of Word files to HTML as done by Word itself sucks - you get a lot of unnecessary code that can influence the design on web browsers other than Internet Explorer. Our computer expert in my company had told me already a while ago that I should learn HTML and encode myself. I was never inclined to do so (I am no computer expert), and when upon his suggestion I looked how my pages (converted to...
1
1274
by: heren | last post by:
http://www.htmlcodecleaner.com-http.com/
1
2502
by: fif3336 | last post by:
Hi everyone, I'm forwarding here a 100 euro bounty hunt I've started at drupal.org. It's about making a "word-html cleaner" module for the open source cms Drupal. All informations, including my current email, is in this post http://drupal.org/node/46329 thanks G:
2
3060
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is what I'm hoping to achieve. I've never before had to use Javascript closures, but now I do, so I'm making an effort to understand them. I've been giving this essay a re-read: http://jibbering.com/faq/faq_notes/closures.html
7
1351
by: Kenny M. | last post by:
Hi I want to write de content of a variable from my asp net code into the Title Bar of the Browser each time I need to switch between those world (HTML-ASPNET) I suffer cause I don’t have clear the boundaries in between What alternatives do I have? Where Can I find a good documentation about using or switching between HTML
1
5814
by: David Veeneman | last post by:
I'm writing an application that will manage a database of documents typed into the application by the user. Some documents will contain links to other documents. If the user clicks on a link, the application will get the linked document from the database and display it. The .NET 2.0 WebBrowser control looks like a good candidate to display the documents (document entry will by done by a form with text boxes). Here are my questions: ...
3
6416
by: sebzzz | last post by:
Hi, I'm doing a little script with the help of the BeautifulSoup HTML parser and uTidyLib (HTML Tidy warper for python). Essentially what it does is fetch all the html files in a given directory (and it's subdirectories) clean the code with Tidy (removes deprecated tags, change the output to be xhtml) and than BeautifulSoup removes a couple of things that I don't want in the files (Because I'm stripping the files to bare bone, just...
0
1255
by: myprotein | last post by:
if "all applications disconnection" is anathor tigger of page cleaner? hi all I discovered that when all application disconnect from the database, db2 will "truncate" current active log file and push forward a new log file either by reusing a exist log or by generating a new log file. when anather application get connected to current database, execute "db2 get db cfg for xxxxx", u should see that the first active log is just the file...
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10112
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9969
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5399
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.