This is the first line of text.
This is the second line of text.
This is the third line of text.
假设要给以下 HTML 代码中的 div 标签中的文本添加 br 标签:
This is the first line of text.
This is the second line of text.
This is the third line of text.
可以使用 Beautiful Soup 库来解决该问题,示例如下:
from bs4 import BeautifulSoup, NavigableString
html = """
This is the first line of text.
This is the second line of text.
This is the third line of text.
"""
soup = BeautifulSoup(html, 'html.parser')
div = soup.find('div', {'class': 'text'})
new_content = []
for content in div.contents:
if isinstance(content, NavigableString):
lines = content.strip().split('\n')
for line in lines:
new_content.append(line)
new_content.append(soup.new_tag('br'))
else:
new_content.append(content)
div.contents = new_content
print(soup.prettify())
输出结果如下:
This is the first line of text.
This is the second line of text.
This is the third line of text.
可以看到,成功地在 div 中的文本中添加了 br 标签。