使用BeautifulSoup对函数中的xml元素进行计数

2024-10-01 00:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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\u len才能工作/我做错了什么


Tags: 文件函数textchildlenreturndefsome
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

你可以这样做

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

相关问题 更多 >