Python 使用BeautifulSoup find_all从最后一个元素获取内容
我试图从find_all创建的列表中的最后一个div中提取内容Python 使用BeautifulSoup find_all从最后一个元素获取内容,python,beautifulsoup,Python,Beautifulsoup,我试图从find_all创建的列表中的最后一个div中提取内容 post\u content=soup.find\u all('div',{'class':'body\u content\u inner'}) 存储以下文本: [<div class="body_content_inner"> post #1 content is here </div>, <div class="body_content_inner"> post #2 content i
post\u content=soup.find\u all('div',{'class':'body\u content\u inner'})
存储以下文本:
[<div class="body_content_inner">
post #1 content is here
</div>, <div class="body_content_inner">
post #2 content is here
</div>]
[
这里有post#1内容
,
第2篇文章的内容在这里
]
我想提取存储在最后一个div标记中的文本,但我不确定如何遍历post\u内容
last_div = None
for last_div in post_content:pass
if last_div:
content = last_div.getText()
然后您将获得最后一项post_内容。html=“”
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
这里有post#1内容
,
第2篇文章的内容在这里
"""
soup=BeautifulSoup(html)
打印soup.find_all(“div”)[-1]。get_text()
第2篇文章的内容在这里
谢谢您的回复。这非常有效,有助于仅分离最后一个div。如何从最后一个div
中提取文本post#2内容在这里?@66Mhz您可以使用getText()
提取文本:-)这确实让我们从A点到B点,但人们喜欢一行。请看Padraic Cunningham的回答。谢谢你的回答。这非常有效,我只需将get_text()
更改为getText()
@66Mhz,不用担心,可能是我的bsoup的不同版本