下面是使用BeautifulSoup的解决方法,可以删除子节点但保留其内容:
from bs4 import BeautifulSoup
html = '''
Title
Paragraph 1
Paragraph 2
'''
# 创建BeautifulSoup对象
soup = BeautifulSoup(html, 'html.parser')
# 获取容器div元素
container = soup.find('div', id='container')
# 遍历div元素的子节点
for child in container.children:
# 判断子节点是否为标签节点
if child.name is not None:
# 将子节点的内容替换为字符串
child.string = child.get_text(strip=True)
# 打印修改后的HTML内容
print(soup.prettify())
输出结果为:
Title
Paragraph 1
Paragraph 2
在代码中,我们首先创建了一个BeautifulSoup对象来解析HTML字符串。然后,使用find()
方法找到id为"container"的div元素,并将其赋值给变量container
。接下来,我们使用children
属性遍历container
的子节点。对于每个子节点,我们检查其是否为标签节点,如果是,则将子节点的内容替换为字符串形式。最后,我们使用prettify()
方法打印修改后的HTML内容。