【发布时间】:2015-02-24 17:46:32
【问题描述】:
我想到了以下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 的回答是肯定的,是效率更高还是内部流程相同?
【问题讨论】:
-
len(soup.find_all('section'))为我显示 2。你有什么问题? -
@AvinashRaj 确实是这样,但是
soup.find_all('section')在传递给len()之前会带来巨大的开销。或者,根本没有开销,它只是一个传递引用的游戏。因此我的问题:) -
我认为没有其他方法了。 stackoverflow.com/questions/13853025/…
-
也许你可以使用 regx。
len(re.findall(r'<section\b[^<>]*>', html)) -
不相信正则表达式。还是)感谢你的建议。我想如果
find_all是官方的计数方式,一定要为此优化。
标签: python xml xml-parsing beautifulsoup