用 BeautifulSoup 替换 python 中的文本

How*_*wli 2 beautifulsoup python-2.7

我正在尝试使用 beautifulSoup 解析表格并删除某些行中的空格 - so 而不是

<tr>
<td><small>15</small></td>
<td><small><small>Cat</small></small></td>
</tr>
<tr>
<td><small><small>   </small></small></td>
<td><small><small> </small></small></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

我想要

<tr>
<td><small>15</small></td>
<td><small><small>Cat</small></small></td>
</tr>
<tr>
<td><small><small>-</small></small></td>
<td><small><small>-</small></small></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

我设法做到了这一点:

from bs4 import BeautifulSoup

soup = BeautifulSoup (open("table.html"))

for a in soup.findAll('small'):
    a.replaceWith("-")
Run Code Online (Sandbox Code Playgroud)

这确实删除了空格,但它也删除了文本 15 和 cat (我知道我用什么替换了标签中的所有内容)。这是我所能得到的。如何修复该代码,以便它只会用 - 替换空格?

编辑:对不起,这是原始代码

<tr>
<td><small>15</small></td >
<td><small><small>&nbsp;</small></small></td >
</tr>
<tr>
<td><small><small>&nbsp; &nbsp;</small></small></td >
<td><small><small>&nbsp;</small></small></td >
</tr>
Run Code Online (Sandbox Code Playgroud)

mor*_*ipo 5

尝试一下:

from BeautifulSoup import BeautifulSoup as bs
soup = bs(open("table.html"))
for i in soup.findAll('small'):
    if i.text == "" or "&nbsp;" in i.text:
        i.string = '-'
print soup
Run Code Online (Sandbox Code Playgroud)

您需要在更换前检查该值。