MohitGhodasara
MohitGhodasara

Reputation: 2742

how to get next tag(element) of the selected tag in beautifulsoup

I want an element that has only HTML tag, not any unique identification but I can select the upper tag of that tag, how can I get next tag form that selection (e.g.)

<div>
    <span class="class1"> text </span>
    <p> I want this text </P> <!-- how to get this text --> 
</div>

code i tried

data = BeautifulSoup("""
    <div>
        <span class="class1"> text </span>
        <p> I want this text </P> <!-- how to get this text -->
    </div>
    """, 'lxml')

data.find('span', class_='class1').next_sibling
data.find('span', class_='class1').next_element

Output:

'\n'
' text '

Upvotes: 0

Views: 389

Answers (1)

ggorlen
ggorlen

Reputation: 57155

Try .find_next_sibling():

data.find('span', class_='class1').find_next_sibling()

Use .text if you'd like to extract the text from the NavigableString object.

Upvotes: 1

Related Questions