使用python / BeautifulSoup将HTML标签对替换为另一对

use*_*609 1 html python tags replace beautifulsoup

我需要用另一个标签替换一对匹配的HTML标签。BeautifulSoup(4)可能适合该任务,但是我以前从未使用过它,并且在任何地方都找不到合适的示例,有人可以给我提示吗?

例如,此HTML代码:

<font color="red">this text is red</font>
Run Code Online (Sandbox Code Playgroud)

应更改为:

<span style="color: red;">this text is red</span>
Run Code Online (Sandbox Code Playgroud)

开头和结尾的HTML标记可能不在同一行。

Mar*_*ers 6

使用replace_with()替换元素。使文档示例适合您的示例将提供:

>>> from bs4 import BeautifulSoup
>>> markup = '<font color="red">this text is red</font>'
>>> soup = BeautifulSoup(markup)
>>> soup.font
<font color="red">this text is red</font>
>>> new_tag = soup.new_tag('span')
>>> new_tag['style'] = 'color: ' + soup.font['color']
>>> new_tag.string = soup.font.string
>>> soup.font.replace_with(new_tag)
<font color="red">this text is red</font>
>>> soup
<span style="color: red">this text is red</span>
Run Code Online (Sandbox Code Playgroud)