【问题标题】:Get text in one tag BS4 python在一个标签BS4 python中获取文本
【发布时间】:2022-01-09 12:05:24
【问题描述】:

我有 HTML 代码。我只需要获取 1 个标签的全文。我用了get_text(),但还是得到了下一个标签的文本。
HTML:

<div class="test__title" data-intro="intro">
    "The first text I need"
    "The second text I need"
    <p class="test__title__promt">
        "I do not need it"
        "I do not need it"
    <p class="test__title__second__promt">
        "I do not need it"
        "I do not need it"

Python:

test_title = soup.find('div', class_='test__title')
print(test_title.get_text())

结果:

The first text I need
The second text I need
I do not need it
I do not need it
I do not need it
I do not need it

想要的结果:

The first text I need
The second text I need

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    注意: 您问题中的html无效,因此输出可能略有不同

    一种方法是获取元素的contents 并获取结果集的第一个元素:

    soup.find('div', class_='test__title').contents[0]
    

    或使用列表推导只选择无标签:

    ' '.join([e.strip() for e in soup.find('div', class_='test__title') if e.name == None])
    

    输出:

    "The first text I need"\n    "The second text I need"
    

    【讨论】:

      猜你喜欢
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 2016-03-26
      • 2021-08-23
      • 1970-01-01
      • 2014-09-23
      • 2020-07-29
      相关资源
      最近更新 更多