使用解析器替换所有IMG元素的SRC [英] Replace SRC of all IMG elements using Parser
问题描述
我正在寻找一种方法来替换不使用正则表达式的所有IMG标记中的SRC属性。 (希望使用默认Python安装中包含的任何现成的HTML解析器)我需要减少可能来源的数据源:
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">
我试图将所有src标记替换为HTML电子邮件附件的cid我还需要更改任何源代码,所以它只是没有路径或扩展名的文件名。
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.
推荐答案
HTML标准库中的HTML解析器,但它不是非常有用,并且自从Python 2.6以来已经被弃用了。使用 BeautifulSoup 做这类事情非常简单:
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)
这篇关于使用解析器替换所有IMG元素的SRC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!