Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get next div when I use BeautifulSoup .findAll?

I work with BeautifulSoup in python2.7 I have code like this:

html = "<div>\
  <div>\
      <div>\
          <div>one</div>\
          <div>\
              <div>two</div>\
              <div>three</div>\
              <div>four</div>\
          </div>\
          <div>five</div>\
      </div>\
  </div>\
</div>"
soup = BeautifulSoup(html,'lxml')
currency = soup.findAll('div')

to get content one i use

print currency[1].div.div.contents

how to get all other: two, three etc.?

like image 713
MastaBot Avatar asked Dec 06 '25 05:12

MastaBot


1 Answers

When you get to the one div, get the following div sibling and then all div elements inside:

one = currency[1].div.div
for elm in one.find_next_sibling("div").find_all("div"):
    print(elm.get_text())

Prints:

two
three
four
like image 72
alecxe Avatar answered Dec 07 '25 19:12

alecxe