avoliva
avoliva

Reputation: 3356

Remove spaces between/after td elements using BeautifulSoup

Anyone have an idea on how you would remove spaces between td elements using beautiful soup?

For example

<table>
  <tr class="soup-target">
    <td></td>     <td></td>
  </tr>
</table>

And before you say "just use the delete key", not possible as I'm using a template language with a loop on the td elements, and the language doesn't allow room to control the spaces or newlines on the looped element.

Upvotes: 1

Views: 364

Answers (2)

alecxe
alecxe

Reputation: 473863

You can also filter the text nodes inside the tr directly and extract them:

row = soup.find("tr", class_="soup-target")
for text_node in row.find_all(text=True, recursive=False):
    text_node.extract()

Upvotes: 1

avoliva
avoliva

Reputation: 3356

Figured this one out

el = soup.find_all('tr', {'class': 'soup-target'})
if el:
    for node in el:
        for child in node.children:
            if isinstance(child, NavigableString):
                child.extract()

Upvotes: 0

Related Questions