【问题标题】:Beautifulsoup4 find and list children with and by nameBeautifulsoup4 查找并按名称列出孩子
【发布时间】:2021-11-17 14:04:48
【问题描述】:

所以我有这个 XML 文件模型:

xml="""
<fruits>
  <fruit>
    <name>apple</name>
    <types>
      <type>
        <color>red</color>
        <taste>sweet</taste>
        <size>big</size>
        <description>Nice, round, sweet red apple</description>
      </type>
      <type>
        <color>green</color>
        <taste>sour</taste>
        <size>medium</size>
        <description>Small, sour, green apple</description>
      </type>
    </types>
  </fruit>
  <fruit>
    <name>Banana</name>
    <types>
      <type>
        <color>yellow</color>
        <taste>sweet</taste>
        <size>small</size>
        <description>Good for banana-smoothies only</description>
      </type>
      <type>
        <color>green</color>
        <taste>Bitter</taste>
        <size>big</size>
        <description>Not quite ripe yet</description>
      </type>
    </types>
  </fruit>
</fruits>
"""
#</editor-fold>

我正在尝试使用此代码:

from bs4 import BeautifulSoup
soup=BeautifulSoup(xml, 'lxml')

fruits=soup.findAll("fruit", recursive=False)
print(fruits)

type=soup.findAll("type")

list=[]

name=soup.findAll("name")

for nameid in range(len(name)):
    list+=name[nameid]

    for id in range(len(type)):
        list+=(soup.findAll("color")[id].string)
        list+=(soup.findAll("taste")[id].string)
        list+=(soup.findAll("size")[id].string)
        list+=(soup.findAll("description")[id].string)
            list+=("""</tr>""")
        #list.append("<td>"+soup.findAll("description")[id].string+"</td>")
        #list.append("</tr>")
        if list:
            list="".join(list)

我无法找到一种方法来列出属性(的孩子),并在表格中列出名称。到目前为止,我尝试的所有操作最终都显示了名称,但是当它碰到香蕉时,它要么只显示苹果的属性,要么显示苹果和香蕉的属性。

我只是在 Python 中通过 BeautifulSoup+lxml 使用 for 循环。任何帮助表示赞赏!

【问题讨论】:

  • 请阅读How to Ask并以minimal reproducible example的形式向我们展示您的尝试。
  • 您尝试从 xml 中提取的信息是什么?使用您尝试构建的数据结构更新帖子。

标签: python xml beautifulsoup


【解决方案1】:

下面的代码会将 xml 中的所有信息收集到一个“有意义”的数据结构中。

代码不使用任何外部库 - 只是核心 python xml 库。

import xml.etree.ElementTree as ET
from collections import defaultdict

xml = """
<fruits>
  <fruit>
    <name>apple</name>
    <types>
      <type>
        <color>red</color>
        <taste>sweet</taste>
        <size>big</size>
        <description>Nice, round, sweet red apple</description>
      </type>
      <type>
        <color>green</color>
        <taste>sour</taste>
        <size>medium</size>
        <description>Small, sour, green apple</description>
      </type>
    </types>
  </fruit>
  <fruit>
    <name>Banana</name>
    <types>
      <type>
        <color>yellow</color>
        <taste>sweet</taste>
        <size>small</size>
        <description>Good for banana-smoothies only</description>
      </type>
      <type>
        <color>green</color>
        <taste>Bitter</taste>
        <size>big</size>
        <description>Not quite ripe yet</description>
      </type>
    </types>
  </fruit>
</fruits>
"""
data = defaultdict(list)
root = ET.fromstring(xml)
for fruit in root.findall('.//fruit'):
    name = fruit.find('name').text
    for _type in fruit.findall('.//type'):
        data[name].append({x.tag: x.text for x in list(_type)})
for fruit, types in data.items():
    print(f'{fruit} -> {types}')

输出

apple -> [{'color': 'red', 'taste': 'sweet', 'size': 'big', 'description': 'Nice, round, sweet red apple'}, {'color': 'green', 'taste': 'sour', 'size': 'medium', 'description': 'Small, sour, green apple'}]
Banana -> [{'color': 'yellow', 'taste': 'sweet', 'size': 'small', 'description': 'Good for banana-smoothies only'}, {'color': 'green', 'taste': 'Bitter', 'size': 'big', 'description': 'Not quite ripe yet'}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    相关资源
    最近更新 更多