使用python/BeautifulSoup将HTML标签对替换为另一对 [英] Using python/BeautifulSoup to replace HTML tag pair with a different one

查看:476
本文介绍了使用python/BeautifulSoup将HTML标签对替换为另一对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to replace a matching pair of HTML tags by another tag. Probably BeautifulSoup (4) would be suitable for the task, but I've never used it before and haven't found a suitable example anywhere, can someone give me a hint?

例如,此HTML代码:

For example, this HTML code:

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

应更改为此:

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

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

The beginning and ending HTML tags may not be in the same line.

推荐答案

使用

Use replace_with() to replace elements. Adapting the documentation example to your example gives:

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

这篇关于使用python/BeautifulSoup将HTML标签对替换为另一对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆