Stripping comments

4 views
Skip to first unread message

Maciej Bliziński

unread,
Sep 22, 2009, 6:06:04 AM9/22/09
to beautifulsoup
Suppose I have a bit of HTML which looks like this: "<span>foo<!-- bar
--></span>". I want to extract the text contained within specific
tags, but without the commented-out text. Here, I'd like to extract
only "foo", without "bar".

>>> import BeautifulSoup as bs
>>> s = bs.BeautifulSoup("<span>foo<!-- bar --></span>")
>>> s.findAll()
[<span>foo<!-- bar --></span>]

This returns the whole <span/> tag, without stripping out the comment,
or returning the comment separately. Do you have any tips how to
extract only "foo" from the above HTML?

Maciej

jitu

unread,
Sep 23, 2009, 3:42:11 AM9/23/09
to beautifulsoup

#http://www.crummy.com/software/BeautifulSoup/
documentation.html#Removing%20elements

comments = s.findAll(text=lambda text:isinstance(text, bs.Comment))
[comment.extract() for comment in comments]
s.findAll()
[<span>foo</span>]

Jitendra Nair
jite...@gslab.com

On Sep 22, 3:06 pm, Maciej Bliziński <maciej.blizin...@gmail.com>
wrote:
Reply all
Reply to author
Forward
0 new messages