【问题标题】:Getting content from last element using BeautifulSoup find_all使用 BeautifulSoup find_all 从最后一个元素中获取内容
【发布时间】:2014-08-26 02:10:36
【问题描述】:

我正在尝试从 find_all 创建的列表中的最后一个 div 中提取内容。

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

存储以下文本:

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

我想提取存储在最后一个 div 标签中的文本,但我不确定如何遍历 post_content

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:
    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
    

    【讨论】:

    • 感谢您的回复。这很好用,我只需将get_text() 更改为getText()
    • @66Mhz,不用担心,可能是我的 bsoup 的不同版本
    【解决方案2】:
    last_div = None
    for last_div in post_content:pass
    if last_div:
        content = last_div.getText()
    

    然后你会得到 post_content 的最后一项。

    【讨论】:

    • 感谢您的回复。这很好用,有助于隔离最后一个 div。如何从last_div 中提取文本post #2 content is here
    • @66Mhz 你可以使用getText() 来提取文本:-)
    • 这确实让我们从 A 点到 B 点,但是人们喜欢单线。看看 Padraic Cunningham 的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多