Beautifulsoup - 在 div 文本中添加 <br> 标签?

尝试使用 beautifulsoup 更改 html 文件。我想在下面 div 类中的每个项目符号点之后添加一个新行。我已经尝试过 text.replace 函数(使用 '\n'),但它在终端之外不起作用,因为 html 只创建带有 br 标签的新行。有没有办法在每个项目符号的末尾插入换行符?

HTML 代码:

<div class="recipe"> ■ Boil water to high heat ■ Put eggs in water ■ Put on lid ■ Wait 8 - 12 minutes ■ Take out eggs ■ Serve</div>

当我在网页上查看它时,它目前看起来像这样:
■ 把水烧开 ■ 将鸡蛋放入水中 ■ 盖上盖子 ■ 等待 8 - 12 分钟 ■ 取出鸡蛋 ■ 上桌

我希望它看起来像这样:
■ 将水烧开至高温
■ 将鸡蛋放入水中
■ 盖上盖子
■ 等待 8 - 12 分钟
■取出鸡蛋
■ 服务

我用来添加新行的代码(仅适用于打印功能)。没有打印功能,它只是将所有的“■”替换为“\n■”,而不会在 html 文件中换行。

for div in soup.find_all("div",{'class':'recipe'}): 
    print(div.text.replace('■','\n■'))
cheng4799 回答:Beautifulsoup - 在 div 文本中添加 <br> 标签?

试试:

from bs4 import BeautifulSoup

html_doc = """
<div class="recipe">
    ■ Boil water to high heat ■ Put eggs in water ■ Put on lid ■ Wait 8 - 12 minutes ■ Take out eggs ■ Serve
</div>"""

soup = BeautifulSoup(html_doc,"html.parser")
recipe = soup.find(class_="recipe")

t = BeautifulSoup(
    "<br />■ ".join(recipe.get_text(strip=True).split("■")).strip("<br />"),"html.parser",)
recipe.string.replace_with(t)

print(soup.prettify())

这将在每个 <br /> 项之后创建 (来自 Firefox 的屏幕截图):

enter image description here

HTML:

<div class="recipe">
 ■  Boil water to high heat
 <br/>
 ■  Put eggs in water
 <br/>
 ■  Put on lid
 <br/>
 ■  Wait 8 - 12 minutes
 <br/>
 ■  Take out eggs
 <br/>
 ■  Serve
</div>

编辑:将 soup 保存到 HTML 文件:

with open("page.html","w") as f_out:
    f_out.write(str(soup))
本文链接:https://www.f2er.com/14275.html

大家都在问