追加文本
若参数是字符串,认为是追加纯文本。若包含 <
、>
等 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('------append 前-----')
print(soup)
content_div = soup.select_one("#content")
content_div.append('<p>追加</p>')
print('------append 后-----')
print(soup)
执行结果:
------append 前-----
<div id="content">
<p>测试01</p>
<span>测试02</span>
</div>
<div>测试03</div>
------append 后-----
<div id="content">
<p>测试01</p>
<span>测试02</span>
<p>追加</p></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('------append 前-----')
print(soup)
content_div = soup.select_one("#content")
new_p = soup.new_tag('p')
new_p.string = '追加'
content_div.append(new_p)
print('------append 后-----')
print(soup)
执行结果:
------append 前-----
<div id="content">
<p>测试01</p>
<span>测试02</span>
</div>
<div>测试03</div>
------append 后-----
<div id="content">
<p>测试01</p>
<span>测试02</span>
<p>追加</p></div>
<div>测试03</div>