Getting content from last element using BeautifulSoup find_all

喜你入骨 提交于 2021-01-27 06:28:35

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/25496999/getting-content-from-last-element-using-beautifulsoup-find-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!