使用BeautifulSoup如何在div文本的项目符号后添加<br>换行标签?
你之前的写法只是修改了打印输出的文本,没有实际修改HTML文件的结构。HTML中换行需要用<br>标签实现,直接在text属性中插入标签会被BeautifulSoup自动转义为普通文本,不会被识别为HTML标签,可按以下代码实现需求:
from bs4 import BeautifulSoup # 此处替换为你自己的HTML源内容 html_source = """ <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_source, 'html.parser') for div in soup.find_all("div", {'class':'recipe'}): # 替换项目符号,同时插入换行标签 replaced_text = div.get_text().replace('■', '<br>■') # 移除开头多余的换行标签(避免第一行前空出一行) replaced_text = replaced_text.lstrip('<br>') # 清空原div内容,将替换后的内容解析为HTML片段插入 div.clear() div.append(BeautifulSoup(replaced_text, 'html.parser')) # 输出修改后的HTML,可写入到文件保存 print(soup.prettify())
处理后对应div的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>
内容的提问来源于stack exchange,提问作者levi_hackerman
相关产品推荐
相关产品推荐

