【问题标题】:Using BeautifulSoup to count xml elements in a function使用 BeautifulSoup 计算函数中的 xml 元素
【发布时间】:2021-12-07 07:29:50
【问题描述】:

我经常使用 len(find_all("some_element") 来计算 xml 文件中的实体数量。我尝试构建一个函数,但它不起作用/它总是给我“无”。

XML 文件:

<parent>
 <some>
   <child>text</child>
   <child>text</child>
   <child>text</child>
 </some>
</parent>

我的python代码:

def return_len(para1,para2): # doesn't work
    if bool(suppe.para1): # the element isn't always present in the xml
        return len(suppe.para1.find_all(para2))

def return_len1(): # does work
    if bool(suppe.some):
        return len(suppe.some.find_all("child"))

print(return_len("some","child")) # doesnt work
print(return_len1()) # does work

我必须如何修改我的函数 return_len 才能开始工作/我做错了什么?

【问题讨论】:

  • 我相信 suppe 是你的 Beautiful Soup 对象。你能分享一下你的实现吗?

标签: python xml beautifulsoup


【解决方案1】:

你可以这样做。

from bs4 import BeautifulSoup

s = """<parent>
 <some>
   <child>text</child>
   <child>text</child>
   <child>text</child>
 </some>
</parent>    
"""

soup = BeautifulSoup(s, 'xml')

def return_len(para1,para2,soup):
    print(f'No. of <{para2}> tags inside <{para1}> tag.')
    temp = soup.find(para1)
    if temp:
        return len(temp.find_all(para2))

print(return_len('some', 'child', soup))
print(return_len('parent', 'some', soup))

No. of <child> tags inside <some> tag.
3
No. of <some> tags inside <parent> tag.
1

【讨论】:

  • 这对我有用!谢谢!
【解决方案2】:

没有任何外部库 - 见下文

import xml.etree.ElementTree as ET


xml = '''<parent>
 <some>
   <child>text</child>
   <child>text</child>
   <child>text</child>
 </some>
</parent>'''

root = ET.fromstring(xml)
print(f'Number of child elements is {len(root.findall(".//child"))}') 

输出

Number of child elements is 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 2023-03-09
    • 1970-01-01
    • 2011-08-12
    相关资源
    最近更新 更多