使用Python/BeautifulSoup替换HTML标签对为其他标签

1 投票
1 回答
4415 浏览
提问于 2025-04-17 19:52

我需要把一对匹配的HTML标签换成另一个标签。可能用BeautifulSoup(4)这个工具比较合适,但我之前没用过,也没找到合适的例子,有人能给我点提示吗?

比如,这段HTML代码:

<font color="red">this text is red</font>

应该改成这样:

<span style="color: red;">this text is red</span>

而且开始和结束的HTML标签不一定在同一行。

1 个回答

8

使用 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>

撰写回答