2010-03-24 40 views
5

我有一個文件這樣之間的兄弟節點:使用BeautifulSoup提取兩個節點

<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 =頂部]和P [CLASS =結束]段落之間的一切。

有沒有一種很好的方式可以用BeautifulSoup做到這一點?

回答

8

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 

這種複雜的情況是,你所訪問的HTML標籤,而不是串節點的屬性是肯定的。