我正在寻找一种方法来替换所有不使用正则表达式的 IMG 标记中的 SRC 属性。(想使用默认 Python 安装中包含的任何开箱即用的 HTML 解析器)我需要将源代码从可能的情况减少到:
<img src="cid:imagename">
我正在尝试替换所有 src 标记以指向 HTML 电子邮件附件的 cid,因此我还需要更改任何源,因此它只是没有路径或扩展名的文件名。
Python 标准库中有一个 HTML 解析器,但它不是很有用,并且自 Python 2.6 起已弃用。用BeautifulSoup做这种事情真的很容易:
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)
这是针对您的问题的 pyparsing 方法。您需要编写自己的代码来转换 http src 属性。
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>