BeautifulSoup排除某个标签内的内容

时间:2014-12-22 20:48:52

标签: python html beautifulsoup html-parsing lxml

我有以下项目来查找段落中的文字:

soup.find("td", { "id" : "overview-top" }).find("p", { "itemprop" : "description" }).text

如何排除<a>标记内的所有文字?像in <p> but not in <a>

这样的东西

2 个答案:

答案 0 :(得分:5)

查找并加入p标记中的所有text nodes,并检查其父级不是a标记:

p = soup.find("td", {"id": "overview-top"}).find("p", {"itemprop": "description"})

print ''.join(text for text in p.find_all(text=True) 
              if text.parent.name != "a")

演示(见编号link text):

>>> from bs4 import BeautifulSoup
>>> 
>>> data = """
... <td id="overview-top">
...     <p itemprop="description">
...         text1
...         <a href="google.com">link text</a>
...         text2
...     </p>
... </td>
... """
>>> soup = BeautifulSoup(data)
>>> p = soup.find("td", {"id": "overview-top"}).find("p", {"itemprop": "description"})
>>> print p.text

        text1
        link text
        text2
>>>
>>> print ''.join(text for text in p.find_all(text=True) if text.parent.name != "a")

        text1

        text2

答案 1 :(得分:1)

使用lxml,

import lxml.html as LH

data = """
<td id="overview-top">
    <p itemprop="description">
        text1
        <a href="google.com">link text</a>
        text2
    </p>
</td>
"""

root = LH.fromstring(data)
print(''.join(root.xpath(
    '//td[@id="overview-top"]//p[@itemprop="description"]/text()')))

产量

        text1

        text2

要获取<p>的子标记文本,只需使用双正斜杠//text(),而不是单个正斜杠:

print(''.join(root.xpath(
    '//td[@id="overview-top"]//p[@itemprop="description"]//text()')))

产量

        text1
        link text
        text2