2014-01-23 29 views
2

我試圖解析與beautifulSoup表,並刪除某些行中發現的空白 - 所以不是替換文本與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和貓(我知道我已經取代了標籤中的所有內容)。就我所能得到的那樣。我該如何修復該代碼,以便只用空格替換空格 - ?

編輯:對不起這裏是原始代碼

<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> 
+0

更換前檢查:如果a.isspace():a.replaceWith(「 - 」) – Mortezaipo

+0

與 '類型錯誤回來:「NoneType」對象不callable' – Howli

+0

我很抱歉,請我我發佈的答案。 – Mortezaipo

回答

2

試試:

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 

需要更換前檢查值。

+0

這並沒有爲我工作,所以我複製了文件中的空間,我得到'SyntaxError:文件中的非ASCII字符'\ xc2'但沒有編碼declated'所以我加了'# - * - coding:latin -1 - * - '現在我得到了'UnicodeWarning:Unicode等於比較無法將這兩個參數轉換爲Unicode - 將它們解釋爲不等於 如果i.text ==「┬á」:' – Howli

+0

@Howlin那個錯誤指向Unicode格式。看看:http://www.python.org/dev/peps/pep-0263/ – Mortezaipo

+0

@霍林請用你的代碼更新你的文章,我可以測試它。 – Mortezaipo