【问题标题】:Using python/BeautifulSoup to replace HTML tag pair with a different one使用 python/BeautifulSoup 将 HTML 标签对替换为不同的标签对
【发布时间】:2013-03-10 20:22:17
【问题描述】:
我需要用另一个标签替换一对匹配的 HTML 标签。可能 BeautifulSoup (4) 适合该任务,但我以前从未使用过它,也没有在任何地方找到合适的示例,有人可以给我提示吗?
例如,这段 HTML 代码:
<font color="red">this text is red</font>
应该改成这样:
<span style="color: red;">this text is red</span>
开始和结束 HTML 标记可能不在同一行。
【问题讨论】:
标签:
python
html
replace
tags
beautifulsoup
【解决方案1】:
使用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>