I am using HTMLParser to extract an image url from a simple html text like this:
html = <p><span style="font-size: 17px;"><span style="color: #993300;"><img style="margin-right: 15px; vertical-align: top;" src="images/announcements.png" alt="announcements" /><cite>some message I would like to preserve with its formatting</cite></span></span></p>
Now I also need a version of the above html without the img tag, but am having difficulty with closing tags in the right spot. Here is what I tried:
class MyHtmlParser(HTMLParser):
'''
Parse simple url to extract data and image url.
This is expecting a simple url containing only one data block and one iimage url.
'''
def __init__(self):
HTMLParser.__init__(self)
self.noImgHtml = ''
def handle_starttag(self, tag, attrs):
if tag == 'img':
for a in attrs:
if a[0] == 'src':
self.imageUrl = a[1]
else:
print '<%s>' % tag
self.noImgHtml += '<%s>' % tag
for a in attrs:
print '%s=%s' % a
self.noImgHtml += '%s=%s' % a
def handle_endtag(self, tag):
self.noImgHtml += '</%s>' % tag
def handle_data(self, data):
self.noImgHtml += data
The output of MyHtmlParser().feed(html) is this:
<b>LATEST NEWS:</b><p><span>style=font-size: 17px;<span>style=color: #993300;</img><cite>The image uploader works again, so make sure to use some screenshots in your uploads/tutorials to make your submission look extra nice</cite></span></span></p>
As you can see (and as is expected from my code flow), the tags aren't closed the way they were in the original html (e.g. span>).
can this be done easily with HTMLParser or should I resort to RE to extract the image tag (which doesn't seem very elegant)?
I can't use external modules to do this so need to make do with what HTMLParser has to offer.
Thanks in advance, frank