插入文本
若插入内容是字符串,认为是插入纯文本。若包含 <
、>
等 HTML 关键字符,会自动进行转义。
from bs4 import BeautifulSoup
html_content = '''
<div id="content">
<p>测试01</p>
<span>测试02</span>
</div>
<div>测试03</div>
'''
soup = BeautifulSoup(html_content, 'html.parser')
print('------插入前-----')
print(soup)
content_div = soup.select_one("#content")
content_div.insert(0, '<p>插入</p>') # 第1个参数是位置,第2个参数是内容
print('------插入后-----')
print(soup)
执行结果:
------插入前-----
<div id="content">
<p>测试01</p>
<span>测试02</span>
</div>
<div>测试03</div>
------插入后-----
<div id="content"><p>插入</p>
<p>测试01</p>
<span>测试02</span>
</div>
<div>测试03</div>
追加 HTML 标签
from bs4 import BeautifulSoup
html_content = '''
<div id="content">
<p>测试01</p>
<span>测试02</span>
</div>
<div>测试03</div>
'''
soup = BeautifulSoup(html_content, 'html.parser')
print('------插入前-----')
print(soup)
content_div = soup.select_one("#content")
new_p = soup.new_tag('p')
new_p.string = '插入'
content_div.insert(0, new_p) # 第1个参数是位置,第2个参数是内容
print('------插入后-----')
print(soup)
执行结果:
------插入前-----
<div id="content">
<p>测试01</p>
<span>测试02</span>
</div>
<div>测试03</div>
------插入后-----
<div id="content"><p>插入</p>
<p>测试01</p>
<span>测试02</span>
</div>
<div>测试03</div>