我正在寻找一种不使用正则表达式的方法来替换所有IMG标签中的SRC属性。(希望使用默认Python安装中包含的任何现成的HTML解析器)我需要将源代码从任何可能的情况下减少为:
<img src="cid:imagename">
我正在尝试将所有的src标签替换为HTML电子邮件中附件的cid,因此我还需要更改源文件名,使其只是不带路径或扩展名的文件名。
我正在寻找一种不使用正则表达式的方法来替换所有IMG标签中的SRC属性。(希望使用默认Python安装中包含的任何现成的HTML解析器)我需要将源代码从任何可能的情况下减少为:
<img src="cid:imagename">
我正在尝试将所有的src标签替换为HTML电子邮件中附件的cid,因此我还需要更改源文件名,使其只是不带路径或扩展名的文件名。
Python标准库中有一个HTML解析器,但它不是很有用,自从Python 2.6版本以来就已经被弃用。使用BeautifulSoup解析HTML非常容易:
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)
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)
标签转换为:
<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>