2010-03-24 4 views
5

ich ein Dokument wie dieses haben:Verwenden BeautifulSoup zu extrahieren Geschwisterknoten zwischen zwei Knoten

<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> 

ich alles zwischen dem p [class = top] und p [class = end] Absätze extrahieren möchten.

Gibt es eine schöne Möglichkeit, dies mit BeautifulSoup zu tun?

Antwort

8

node.nextSibling Attribut ist Ihre Lösung:

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 

Diese komplizierte Bedingung ist sicher sein, dass Sie Attribute von HTML-Tags und nicht die Zeichenfolge Knoten zugreifen.

Verwandte Themen