依次对html文本中的img标签替换成不同内容

业务场景:将公司富文本编辑器生成的html文本使用百家号的接口进行发送,但是百家号对html文本里的img标签做了限制,标签里的图片链接如果不是它们的域名便不能发送。有预感将来还会出现这样的需求,写个博客记录一下。

import re
from lxml import etree

html, new_html = '', ''

tree = etree.HTML(html)
new_tag_list = tree.xpath('//img/@src')
split_all = re.split('<img[^>]+>', html)  # 如果需要匹配其他标签修改成相应的正则即可

for new_tag, split_piece in zip(new_tag_list, split_all):
    new_html += (split_piece + new_tag)
new_html = new_html + split_all[-1]
复制代码

转载于:https://juejin.im/post/5d022024f265da1bd305545d

猜你喜欢

转载自blog.csdn.net/weixin_34355881/article/details/93179210
今日推荐