【问题标题】:Get text of HTML tags without text of inner child tags获取没有内部子标签文本的 HTML 标签文本
【发布时间】:2015-05-11 02:57:50
【问题描述】:

例子:

有时 HTML 是:

<div id="1">
    <div id="2">
        this is the text i do NOT want
    </div>
    this is the text i want here
</div>

其他时候只是:

<div id="1">
    this is the text i want here
</div>

我只想获取一个标签中的文本,而忽略所有其他子标签。如果我运行 .text 属性,我会得到两者。

【问题讨论】:

  • 为什么不获取outer的文本并替换其直接子节点的所有文本?
  • @tuananh 如果直接子项的文本也是 &lt;div&gt;a b c&lt;div&gt;b&lt;/div&gt;e f&lt;/div&gt; 中的父项中的字符串的一部分,您怎么知道要替换什么?
  • 文本是否保证跟随任何和所有内部子标签?

标签: python python-2.7 beautifulsoup


【解决方案1】:

另一种可能的方法(我会在函数中实现):

def getText(parent):
    return ''.join(parent.find_all(text=True, recursive=False)).strip()

recursive=False 表示您只想要直接子代,而不是嵌套子代。而text=True 表示您只需要文本节点。

使用示例:

from bs4 import BeautifulSoup

html = """<div id="1">
    <div id="2">
        this is the text i do NOT want
    </div>
    this is the text i want here
</div>
"""
soup = BeautifulSoup(html)
print(getText(soup.div))
#this is the text i want here

【讨论】:

    【解决方案2】:

    更新以使用更通用的方法(请参阅编辑历史以获取原始答案):

    您可以通过测试它们是否是NavigableString的实例来提取外部div的子元素。

    from bs4 import BeautifulSoup, NavigableString
    
    html = '''<div id="1">
        <div id="2">
            this is the text i do NOT want
        </div>
        this is the text i want here
    </div>'''
    
    soup = BeautifulSoup(html)    
    outer = soup.div
    inner_text = [element for element in outer if isinstance(element, NavigableString)]
    

    这会产生一个包含在外部 div 元素中的字符串列表。

    >>> inner_text
    [u'\n', u'\n    this is the text i want here\n']
    >>> ''.join(inner_text)
    u'\n\n    this is the text i want here\n'
    

    第二个例子:

    html = '''<div id="1">
        this is the text i want here
    </div>'''
    soup2 = BeautifulSoup(html)    
    outer = soup2.div
    inner_text = [element for element in outer if isinstance(element, NavigableString)]
    
    >>> inner_text
    [u'\n    this is the text i want here\n']
    

    这也适用于其他情况,例如外部 div 的文本元素出现在任何子标签之前、子标签之间、多个文本元素或根本不存在。

    【讨论】:

    • 我并不总是知道它是否会有内部标签。
    • 如果文本恰好在内部&lt;div&gt;之前,或者之前和之后,则第一种方法不起作用。如果文本是之前的,第二个版本会给出错误的文本。
    • 而且由于内部&lt;div&gt; 是可选的,所以第一个不起作用?
    • @Anthon:是的,我最初的答案完全基于 OP 的示例。我已经用通用解决方案更新了答案。
    • @mhawke OP 后来扩展了示例并表示这些示例具有代表性。如果从一开始就很清楚,我不会评论您的原始解决方案可能存在的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多