views:

453

answers:

3

Python Newbie. I am looking for a way to replace the SRC attribute in all IMG tags not using Regular expressions. (would like to use any out-of-the box HTML parser included with default Python install) I need to reduce the source from what ever it may be to:

<img src="cid:imagename">

I am trying to replace all src tags to point to the cid of an attachment for an html email so I will also need to change whatever the source is so it's simply the file name without the path or extension. Thanks in advance

+1  A: 

You'll probably want to use BeautifulSoup for parsing HTML.

tgray
+2  A: 

There is a HTML parser in the Python standard library, but it's not very useful and it's deprecated since Python 2.6. Doing this kind of things with BeautifulSoup is really easy:

from BeautifulSoup import BeautifulSoup
from os.path import basename, splitext
soup = BeautifulSoup(my_html_string)
for img in soup.findAll('img')
    img['src'] = 'cid:' + splitext(basename(img['src']))[0]
my_html_string = str(soup)
Lukáš Lalinský
Thanks for this example. I appreciate it greatly!
CPCase
A: 

Here is a pyparsing approach to your problem. You'll need to do your own code to transform the http src attribute.

from pyparsing import *
import urllib2

imgtag = makeHTMLTags("img")[0]

page = urllib2.urlopen("http://www.yahoo.com")
html = page.read()
page.close()

# print html

def modifySrcRef(tokens):
    ret = "<img"
    for k,i in tokens.items():
        if k in ("startImg","empty"): continue
        if k.lower() == "src":
            # or do whatever with this
            i = i.upper() 
        ret += ' %s="%s"' % (k,i)
    return ret + " />"

imgtag.setParseAction(modifySrcRef)

print imgtag.transformString(html)

The tags convert to:

<img src="HTTP://L.YIMG.COM/A/I/WW/BETA/Y3.GIF" title="Yahoo" height="44" width="232" alt="Yahoo!" />
<a href="r/xy"><img src="HTTP://L.YIMG.COM/A/I/WW/TBL/ALLYS.GIF" height="20" width="138" alt="All Yahoo! Services" border="0" /></a>
Paul McGuire
Thanks so much for this. I will try it out. I appreciate your time and help!
CPCase