I thought about the following while writing an answer to this question.
Suppose I have a deeply nested xml
file like this (but much more nested and much
BeautifulSoup
cannot give you just a count/number of tags it found.
What you, though, can improve is: don't let BeautifulSoup
go searching sections inside other sections by passing recursive=False
:
len(soup.find_all("section", recursive=False))
Aside from that improvement, lxml
would do the job faster:
tree.xpath('count(//section)')