业务场景:将公司富文本编辑器生成的html文本使用百家号的接口进行发送,可是百家号对html文本里的img标签作了限制,标签里的图片连接若是不是它们的域名便不能发送。有预感未来还会出现这样的需求,写个博客记录一下。html
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]
复制代码