我正在尝试用beautifulSoup解析一个表并删除某些行中的空格 - 所以而不是
<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>
我想要
<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>
我有点设法做到这一点:
from bs4 import BeautifulSoup
soup = BeautifulSoup (open("table.html"))
for a in soup.findAll('small'):
a.replaceWith("-")
这确实删除了空格,但它也删除了文本15和cat(我知道我已经替换了标签中的所有内容)。就我所能得到的而言。如何修复该代码,以便只用 - ?
替换空格编辑:对不起,这是原始代码
<tr>
<td><small>15</small></td >
<td><small><small> </small></small></td >
</tr>
<tr>
<td><small><small> </small></small></td >
<td><small><small> </small></small></td >
</tr>
答案 0 :(得分:3)
试一试:
from BeautifulSoup import BeautifulSoup as bs
soup = bs(open("table.html"))
for i in soup.findAll('small'):
if i.text == "" or " " in i.text:
i.string = '-'
print soup
您需要在更换前检查该值。