BeautifulSoup excludes content within a specific tag (s)

I have the following paragraph to find text in a paragraph:

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

How can I exclude all text in a tag <a>? Something like in <p> but not in <a>?

+4
source share
2 answers

Find and attach all the text nodes in the tag pand make sure that it is not a tag 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")

Demo (not printed 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
+4
source

Using 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()')))

gives

        text1

        text2

To get the text of child tags <p>, just use a double slash //text()instead of a single slash:

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

gives

        text1
        link text
        text2
+1
source

Source: https://habr.com/ru/post/1568669/


All Articles