[英]Beautifulsoup - add <br> tag in div text?
嘗試使用 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■'))
嘗試:
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 的截圖):
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.