Skip to content Skip to sidebar Skip to footer

Printing Only Outer Tags In HTML Code Using BeautifulSoup

Part of whole HTML code looks as follows

Solution 1:


Solution 2:

You can extract all elements inside td.col2 with extract() function:

data = '''
<td class="col2">
<a class="reserve" data-target="#myModal" data-toggle="modal"
href="example.com" rel="nofollow"></a></td>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'lxml')

for td in soup.select('td.col2'):
    for t in td.select('*'):
        t.extract()
    print(td)

Prints:

<td class="col2">
</td>

Post a Comment for "Printing Only Outer Tags In HTML Code Using BeautifulSoup"