代码之家  ›  专栏  ›  技术社区  ›  Oli

使用BeautifulSoup提取两个节点之间的兄弟节点

  •  7
  • Oli  · 技术社区  · 16 年前

    <p class="top">I don't want this</p>
    
    <p>I want this</p>
    <table>
       <!-- ... -->
    </table>
    
    <img ... />
    
    <p> and all that stuff too</p>
    
    <p class="end>But not this and nothing after it</p>
    

    我想提取p[class=top]和p[class=end]段落之间的所有内容。

    有什么好方法可以让我和BeautifulSoup一起做吗?

    1 回复  |  直到 16 年前
        1
  •  8
  •   Łukasz    16 年前

    node.nextSibling 属性是您的解决方案:

    from BeautifulSoup import BeautifulSoup
    
    soup = BeautifulSoup(html)
    
    nextNode = soup.find('p', {'class': 'top'})
    while True:
        # process
        nextNode = nextNode.nextSibling
        if getattr(nextNode, 'name', None)  == 'p' and nextNode.get('class', None) == 'end':
            break