【问题标题】:How to Extract the last paragraph tag text in beautifulsoup?如何在beautifulsoup中提取最后一段标签文本?
【发布时间】:2018-08-11 12:09:12
【问题描述】:

我正在解析的 html 文件有多个 <p> 标签如下:

<p>first text</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>my text</p>

在这里打印第一段文字:first text

print (soup.find("section", {"id": "posts"}).article.div.p.text)

如何打印最后一个:my text

【问题讨论】:

  • .findAll 并选择最后一个?
  • find_next_sibling解决了

标签: python html python-3.x beautifulsoup


【解决方案1】:

使用find_all获取所有p作为列表,获取最后一个元素,然后引用它的text属性

soup.find("section", {"id": "posts"}).article.div.find_all('p')[-1].text

【讨论】:

    【解决方案2】:

    问题可以使用find_next_siblings方法解决:

    例如提取第四个&lt;p&gt;标签

    l1 = soup.find("section", {"id": "posts"}).article.div.p
    l2 = l1.find_next_sibling('p')
    l2 = l2.find_next_sibling('p')
    l2 = l2.find_next_sibling('p')
    
    print (l2.text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多