【问题标题】:To remove tags containing particular subtag in xml parsing with BeautifulSoup使用 BeautifulSoup 在 xml 解析中删除包含特定子标签的标签
【发布时间】:2018-05-01 09:34:01
【问题描述】:
我正在尝试在 Python 中使用 BeautifulSoup 解析 XML 文件。 XML文件如:
<x id = '123'>
<b><c>abcd</c>
</b>
</x>
<x id ='456'><z></z>
</x>
<x id ='567'><c>def</c>
</x>
如果任何外部标签<x>包含子标签<c>,我想删除整个标签。我应该如何在 Python 中做到这一点?
【问题讨论】:
标签:
python
xml
beautifulsoup
【解决方案1】:
首先,使用find_all('x') 查找所有x 标签。然后如果标签包含<c>标签(可以使用if x.find('c'):检查)使用decompose()删除标签。
xml = '''
<x id = '123'>
<b><c>abcd</c></b>
</x>
<x id ='456'>
<z></z>
</x>
<x id ='567'>
<c>def</c>
</x>'''
soup = BeautifulSoup(xml, 'html.parser')
for x in soup.find_all('x'):
if x.find('c'):
x.decompose()
print(soup)
输出:
<x id="456">
<z></z>
</x>