【问题标题】:XML 2x the same siblings in xml, how do i get the second one?XML 2x xml 中相同的兄弟姐妹,我如何获得第二个?
【发布时间】:2020-12-08 13:49:50
【问题描述】:

我有一个 xml 提要,我想从 xml 的这一行获取 te 类别和子类别:

与:

cat = x.find('categories/category/cat/title').text

我只得到第一个(vibo's),还需要(Vibrator Speciaal

<categories>
<category>
<cat>
<id>1</id>
<title>Vibo's</title> //Need this one
</cat>
<cat>
<id>182</id>
<title>Vibrator Speciaal</title> //and need this one
</cat>
</category>
</categories>

无法按我的意愿工作

【问题讨论】:

  • 使用find_all 而不是find - 它给出了所有元素的列表。然后使用for-loop 从所有元素中获取文本。或cat_list[1] 从列表中获取第二个元素。

标签: python xml-parsing


【解决方案1】:

我认为你可以使用 lxml 和 XPath 表达式来做到这一点:

from lxml import etree
tree = etree.parse("yourXMLFile.xml")
for title in tree.xpath("/categories/category/cat/title"):
    print(title.text)

【讨论】:

    【解决方案2】:

    如果您使用BeautifulSoup,那么您应该使用find_all 而不是find

    cat = soup.find_all('title')
    

    它给出了所有元素的列表,然后你可以使用for-loop

    for item in cat:
        print(item.text)
    

    或索引或切片

    print(cat[1].text)
    

    编辑:在其他模块中可能有名称findall

    text = """
    <categories>
    <category>
    <cat>
    <id>1</id>
    <title>Vibo's</title> //Need this one
    </cat>
    <cat>
    <id>182</id>
    <title>Vibrator Speciaal</title> //and need this one
    </cat>
    </category>
    </categories>
    """
    
    # -----
    
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(text, 'html.parser')
    
    cat = soup.find_all('title')
    
    for item in cat:
        print(item.text)
    
    # OR
    print(cat[1].text)
    
    # -----
    
    import lxml.etree
    
    soup = lxml.etree.fromstring(text)
    
    cat = soup.findall('.//title')
    
    for item in cat:
        print(item.text)
    
    # OR
    print(cat[1].text)
    

    【讨论】:

      【解决方案3】:

      感谢您的所有快速回答!

      这对我来说非常适合!感谢您的帮助

      cat = x.findall('categories/category/cat/title')
      print(blabla, blabla, blabla, cat[1].text)
      print(blabla, blabla, blabla, cat[0].text)
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-21
        • 2020-05-27
        • 2021-01-10
        • 1970-01-01
        • 2012-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多