【问题标题】:Extract text in BeautifulSoup except for one tag提取 BeautifulSoup 中除一个标签外的文本
【发布时间】:2013-10-31 13:18:11
【问题描述】:

我正在尝试使用 BeautifulSoup 提取文本。

这里是html:

<div>
    "BLABLA"
    <span> "RRRRR" </span>
    <span> "ZZZZZ" </span>
</div>

我只想得到'BLABLA''RRRR' 并搭上'ZZZZ'

当然soup.text给了我3条短信。

一种解决方案是迭代直到我找到第二个跨度(如在这个问题中:How to get all text between just two specified tags using BeautifulSoup?

但是在这种情况下有更好的解决方案吗?

【问题讨论】:

  • 为什么你找到的方法不起作用?正则表达式是一种选择
  • 它会起作用的。我只是想知道在这种情况下是否有更好的解决方案(这与我找到的解决方案不同)。
  • 如果你有这个 html,那么你可以这样做:soup.div.contents[0]soup.div.span.text。如果没有,那就没有更好的方法了。

标签: python beautifulsoup screen-scraping


【解决方案1】:

您可以使用以下代码(您可以根据需要进行修改):

from bs4 import BeautifulSoup, NavigableString

html = '''
<div>
    "BLABLA"
    <span> "RRRRR" </span>
    <span> "ZZZZZ" </span>
</div>'''
soup = BeautifulSoup(html, 'lxml')

wanted_text = [x.strip() if isinstance(x, NavigableString) else x.text.strip() for x in soup.find('div').contents[:2]]
print(wanted_text)
# ['"BLABLA"', '"RRRRR"']

如果 HTML 发生了一些变化,您只需更改切片索引(即将contents[:2] 更改为您需要的任何内容)。

【讨论】:

    猜你喜欢
    • 2015-10-22
    • 1970-01-01
    • 2019-05-11
    • 2023-04-02
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多