【问题标题】:How to get the text in a particular div avoiding the text from nested divs via BS4如何通过 BS4 获取特定 div 中的文本,避免嵌套 div 中的文本
【发布时间】:2020-06-05 00:39:24
【问题描述】:

结构是这样的

<div>
  <div>some text</div>
  <div>some text</div>
  98
</div>

如何通过 BeautifulSoup 仅获取 '98' 忽略其他嵌套 div 中的文本

一段代码:

<div class="b-stickiness js-stickiness">
 <div class="b-stickiness__ico">
  <svg class="sc-icon" data-group="xs" data-name="ChartPie" fill="currentColor" height="12" preserveaspectratio="xMidYMid meet" viewbox="0 0 12 12" width="12">
   <path d="M6 1v5h5c0-2.761-2.239-5-5-5zm-1 1c-2.761 0-5 2.239-5 5s2.239 5 5 5 5-2.239 5-5h-5v-5z" shape-rendering="geometricPresision">
   </path>
  </svg>
  <div class="b-stickiness__tooltip js-tooltip">
   <div class="b-stickiness__tooltip__inner">
    <div class="b-stickiness__tooltip__title">
     Wow-Score
    </div>
    <div class="b-stickiness__tooltip__text">
     The Wow-Score shows how engaging a blog post is. It is calculated based on the correlation between users’ active reading time, their scrolling speed and the article’s length.
    </div>
    <a class="b-stickiness__tooltip__btn js-stickiness-btn" data-type="min" href="/wow-score/about/" title="Learn more">
     Learn more
    </a>
   </div>
  </div>
 </div>
 99
</div>

我想得到那个 99

【问题讨论】:

标签: python html python-3.x beautifulsoup


【解决方案1】:

使用findAll() 然后这些参数:

string=True - 仅搜索字符串。 docs
recursive=False - 不要看孩子。 docs

from bs4 import BeautifulSoup
soup = BeautifulSoup("<div><div>some text</div><div>some text</div>98</div>", "html.parser")

soup.div.findAll(string=True, recursive=False)[-1]

>>> '98'

【讨论】:

  • 伙计,这绝对是我需要的,但我不明白为什么它不能与我的代码一起使用。我已将其添加到我的问题中,请帮助
  • 谢谢!问题是代码中有一个更高的空间,所以我得到了空间。我的代码的完整决定如下所示: number = social.div.findAll(string=True, recursive=False)[1].replace('\n','')
【解决方案2】:

尝试使用div:nth-child(2) 获取下一个div.next_sibling 在元素之间导航

例子

from bs4 import BeautifulSoup

html = """
<div>
  <div>some text 1</div>
  <div>some text 2</div>
  98
</div>
"""

page_soup = BeautifulSoup(html, "html.parser")
print(page_soup.select("div:nth-child(2)")[0].next_sibling)

打印出来98

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-19
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2014-12-03
    相关资源
    最近更新 更多