66Mhz
66Mhz

Reputation: 225

Getting content from last element using BeautifulSoup find_all

I'm trying to extract the content from the last div in in a list created by find_all.

post_content = soup.find_all('div',{'class': 'body_content_inner'})

stores the following text:

[<div class="body_content_inner">
 post #1 content is here
 </div>, <div class="body_content_inner">
 post #2 content is here
 </div>]

I'd like to extract the text that is stored within the last div tag but I am unsure how to iterate through post_content

Upvotes: 5

Views: 34356

Answers (2)

atupal
atupal

Reputation: 17210

last_div = None
for last_div in post_content:pass
if last_div:
    content = last_div.getText()

And then you get the last item of post_content.

Upvotes: 5

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

html = """
<div class="body_content_inner">
 post #1 content is here
 </div>, <div class="body_content_inner">
 post #2 content is here
 </div>
  """
soup = BeautifulSoup(html)
print soup.find_all("div")[-1].get_text()
post #2 content is here

Upvotes: 48

Related Questions