【问题标题】:Beautiful soup 4: Extract text with no tags美汤4:提取无标签文本
【发布时间】:2017-03-16 13:08:11
【问题描述】:
<li class="actualPrice price fakeLink " data-automation="actual-price">
       <span class="visuallyhidden">Hello world</span>
Some text I want to extract
</li>

这里有一些 HTML。 我想提取文本“我想提取的一些文本”,我不想提取 Hello world。

我尝试过类似 find('span') 并使用 next_sibling 但我没有。

for a in soup.find_all('li', 'actualPrice'):
        print a.get_text()

这给了我 Hello world 和“我想提取的一些文本”。 有没有只提取“我想提取的一些文本”的方法?

【问题讨论】:

  • a.span.next.next 会给你Some text I want to extract

标签: python html beautifulsoup


【解决方案1】:

如果你想在span标签之后提取下一个元素,那么你可以使用.next:

>>> for a in soup.find_all('li', 'actualPrice'):
        print(a.span.next.next)
Some text I want to extract

【讨论】:

    【解决方案2】:

    只是为了另一种方法,您可以使用stripped_strings:

    for li in soup.find_all('li', 'actualPrice'):
        _, text_you_want = li.stripped_strings
        print (text_you_want)
    

    输出:

    我要提取的一些文本

    【讨论】:

      猜你喜欢
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 2021-05-24
      相关资源
      最近更新 更多