如何用BeautifulSoup为<item>内的多个<p>标签统一包裹<content>标签?
问题与解决方案
需求描述
需要为每个<item>标签内的所有<p>标签统一包裹一个<content>标签,且<item>内的<title>标签需位于<content>标签外部。
源文件内容
<item> <title>Heading for Sec 1</title> <p>some text sec 1</p> <p>some text sec 1</p> <p>some text sec 1</p> </item> <item> <title>Heading for Sec 2</title> <p>some text sec 2</p> <p>some text sec 2</p> <p>some text sec 2</p> </item> <item> <title>Heading for Sec 3</title> <p>some text sec 3</p> <p>some text sec 3</p> </item>
期望输出
<item> <title>Heading for Sec 1</title> <content> <p>some text sec 1</p> <p>some text sec 1</p> <p>some text sec 1</p> </content> </item> <item> <title>Heading for Sec 2</title> <content> <p>some text sec 2</p> <p>some text sec 2</p> <p>some text sec 2</p> </content> </item> <item> <title>Heading for Sec 3</title> <content> <p>some text sec 3</p> <p>some text sec 3</p> </content> </item>
问题代码
以下代码会为每个<p>单独包裹<content>,不符合需求:
from bs4 import BeautifulSoup with open('testdoc.txt', 'r') as f: soup = BeautifulSoup(f, "html.parser") content = None for tag in soup.select("p"): if tag.name == "p": content = tag.wrap(soup.new_tag("content")) content.append(tag) continue print(soup)
修正方案
问题出在遍历单个<p>标签,导致每个<p>都被单独包裹。正确做法是按<item>为单位处理,将每个<item>内的所有<p>统一放入同一个<content>标签中。
修正后的代码:
from bs4 import BeautifulSoup with open('testdoc.txt', 'r') as f: soup = BeautifulSoup(f, "html.parser") # 遍历每个item标签 for item in soup.find_all("item"): # 获取当前item下的所有p标签 p_tags = item.find_all("p") if not p_tags: continue # 创建content标签 content_tag = soup.new_tag("content") # 将所有p标签移动到content标签内 for p in p_tags: content_tag.append(p) # 找到当前item下的title标签,在其后面插入content标签 title_tag = item.find("title") title_tag.insert_after(content_tag) # 输出处理后的内容 print(soup.prettify())
代码说明
- 遍历每个
<item>标签,确保每个<item>单独处理; - 提取当前
<item>内的所有<p>标签,若没有则跳过; - 创建新的
<content>标签,将所有<p>标签依次移入其中; - 找到
<item>内的<title>标签,在其后面插入<content>标签,保证<title>在<content>外部; - 使用
prettify()方法格式化输出,保持代码结构清晰。
内容的提问来源于stack exchange,提问作者elbourne
相关产品推荐
相关产品推荐

