我想到了以下while writing an answer to this question .
假设我有一个像这样的深度嵌套的 xml
文件(但嵌套更多且更长):
<section name="1">
<subsection name"foo">
<subsubsection name="bar">
<deeper name="hey">
<much_deeper name"yo">
<li>Some content</li>
</much_deeper>
</deeper>
</subsubsection>
</subsection>
</section>
<section name="2">
... and so forth
</section>
len(soup.find_all("section"))
的问题是,在执行 find_all("section")
时,BS 会不断深入搜索一个标签,该标签我知道不会包含任何其他 section
标记。
那么,有两个问题:
- 有没有办法让 BS 不递归搜索已找到的标签?
- 如果 1 的答案是肯定的,它会更高效还是内部流程相同?
最佳答案
BeautifulSoup
无法仅向您提供它找到的标签的计数/数量。
不过,您可以改进的是:不要让 BeautifulSoup
通过传递 recursive=False
来搜索其他部分中的部分:
len(soup.find_all("section", recursive=False))
除了这一改进之外,lxml
还能更快地完成这项工作:
tree.xpath('count(//section)')
关于python - BeautifulSoup 计算标签而不深入解析它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673644/