BeautifulSoup counting tags without parsing deep inside them

前端 未结 1 1437
遥遥无期
遥遥无期 2021-01-16 02:54

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

1条回答
  •  离开以前
    2021-01-16 03:14

    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)')
    

    0 讨论(0)
提交回复
热议问题