示例
from bs4 import BeautifulSoup
html_content = '''
<div id="content" data="你好">
<p>测试01</p>
</div>
<span>测试02</span>
<p>测试03</p>
'''.strip()
soup = BeautifulSoup(html_content, 'html.parser')
print('''------ 处理前 ------''')
print(soup)
print('''------ 处理 ------''')
new_div = soup.new_tag('div')
span_element = soup.select_one('span')
span_element.wrap(new_div)
print('''------ 处理后 ------''')
print(soup)
执行结果:
------ 处理前 ------
<div data="你好" id="content">
<p>测试01</p>
</div>
<span>测试02</span>
<p>测试03</p>
------ 处理 ------
------ 处理后 ------
<div data="你好" id="content">
<p>测试01</p>
</div>
<div><span>测试02</span></div>
<p>测试03</p>