【问题标题】:how to get to the most inner XML of a recursive node in beautiful soup如何在美丽的汤中获取递归节点的最内部 XML
【发布时间】:2014-10-06 08:54:15
【问题描述】:

使用此代码

<BrowseNodes>
    <BrowseNode>
        <BrowseNodeId>3404981</BrowseNodeId>
        <Name>Tires</Name>
        <Ancestors>
            <BrowseNode>
                <BrowseNodeId>6388965011</BrowseNodeId>
                <Name>Tires & Tubes</Name>
                <Ancestors>
                    <BrowseNode>
                        <BrowseNodeId>3403201</BrowseNodeId>
                        <Name>Cycling</Name>
                        <Ancestors>
                            <BrowseNode>
                                <BrowseNodeId>3375301</BrowseNodeId>
                                <Name>Categories</Name>
                                <IsCategoryRoot>1</IsCategoryRoot>
                                <Ancestors>
                                    <BrowseNode>
                                        <BrowseNodeId>3375251</BrowseNodeId>
                                        <Name>Sports & Outdoors</Name>
                                    </BrowseNode>
                                </Ancestors>
                            </BrowseNode>
                        </Ancestors>
                    </BrowseNode>
                </Ancestors>
            </BrowseNode>
        </Ancestors>
    </BrowseNode>
</BrowseNodes>

我正在尝试使用漂亮的汤来获得最内部的节点。在这种情况下,“运动与户外”。因为我不知道一个 BrowseNode 可以进入多少层,如果假设最内层是我需要的根,我如何获得最内层?

谢谢

【问题讨论】:

  • 是什么让Sports &amp; Outdoors3375251 更深入人心?
  • 它没有......我的问题是关于 标签......我不知道它会走多远。这对我来说意味着它是递归的。我想要的是最里面 标签的 值。谢谢。
  • 好的,您是否必须处理BrowseNode 可能有两个BrowseNode 孩子的可能性,其中一个孩子比另一个孩子更深,或者您可以相信每个@ 987654326@ 下面正好有 0 或 1 个 BrowseNodes?

标签: python python-3.x beautifulsoup


【解决方案1】:

如果您真的需要在文档中的任何位置获取嵌套最深的一个,您可以查看所有这些,然后计算父级。在非大型文档上性能应该没问题。注意:这不处理 2 个这样的元素与兄弟元素具有相同深度或位于不同位置的情况。

depths = (
    (elem, sum(1 for p in elem.parents if p.name == 'BrowseNode'))
    for elem in soup.findAll('BrowseNode'))
deepest_elem, deepest_depth = max(depths, key=lambda t:t[1])

【讨论】:

    【解决方案2】:

    如果你可以相信每个BrowseNode 要么有一个BrowseNode 后代,要么没有,这很简单:

    def deepest(root, tag):
       descendant = root.find(tag)
       if descendant:
           return deepest(descendant, tag)
       return root
    

    (你可以让它更简洁,但我想让逻辑尽可能清晰。)

    如果 BrowseNode 可能有 2 个或更多 BrowseNode 后代,并且您必须找到最深的后代,那么您必须修改它以进行深度优先搜索。这不是太难;你只需要让deepest返回(level, node)而不是node,使用find_all而不是find,然后使用max(deepest(descendant, tag) for descendant in descendants)

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 2018-09-13
      • 2011-11-15
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      相关资源
      最近更新 更多