【问题标题】:Python Beautifulsoup XML Tags with Same Name具有相同名称的 Python Beautifulsoup XML 标记
【发布时间】:2018-04-18 17:53:40
【问题描述】:

假设我有以下具有嵌套层次结构的最小 xml。如何隔离第一次出现,然后隔离后续的嵌套出现?

<test name='something'>
<tag max='10' min='20'>
    <tag max='5' min='20'/>
    <tag max='5' min='20'/>
</first>

理想情况下,我将能够解析出第一个标签中的信息,然后解析嵌套标签中的信息。

我尝试使用第一个标签的contents,但我也得到了所有嵌套标签。

预期的输出是:

  1. &lt;tag max='10' min='20'&gt;
  2. <tag max='5' min='20'/> <tag max='5' min='20'/>

【问题讨论】:

  • 提供更多详细信息,例如预期输出和您的输入
  • 你不清楚你想要什么,首先提供更好的 xml 内容,因为你的 xml 似乎明显损坏并且输出正确

标签: python xml beautifulsoup


【解决方案1】:

我已尽力使用您提供的 XML。我假设您提供了一个不完整的 XML。

我在 BeautifulSoup 中使用了decompose() 函数来帮助您实现目标。

代码:

from bs4 import BeautifulSoup
import requests

data = '''
<test name='something'>
<tag max='10' min='20'>
    <tag max='5' min='20'/>
    <tag max='5' min='20'/>
</first>
'''

soup = BeautifulSoup(data, 'html.parser')
[print(i) for i in soup.find_all('tag', max='5')]
print('*********************************')
[i.decompose() for i in soup.find_all('tag', max='5')]
print(soup.find('tag', max='10'))

输出:

<tag max="5" min="20"></tag>
<tag max="5" min="20"></tag>
*********************************
<tag max="10" min="20">


</tag>

【讨论】:

  • 我确实相信 .decompose() 函数是我正在寻找的。与其子标签名称相同的父标签让我失望。我将进一步研究 .decompose() 函数。而且,是的,它是一个不完整的 xml,只是一个更大文档的 sn-p。
猜你喜欢
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 2015-05-06
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多