2013-06-20 46 views
2

我的代碼:BeautifulSoup和 

html = "<tag>&nbsp;</tag>" 
from bs4 import BeautifulSoup 
print BeautifulSoup(html).renderContents() 

輸出:

<tag> </tag> 

所需的輸出:

<tag>&nbsp;</tag> 

BeautifulSoup似乎取代了我打破空間的HTML逃生使用Unicode字符這意味着同樣的事情。但是,這並不能完全通過我的系統,最終成爲一個不間斷的空間,因此不能做我想做的事。有沒有辦法告訴BeautifulSoup不這樣做?

回答

5

使用encode_contents而不是renderContentsencodeprettify。它們都支持formatter參數,並通過'html'爲格式化:

html = "<tag>&nbsp;</tag>" 
from bs4 import BeautifulSoup 
print BeautifulSoup(html).encode_contents(formatter='html') 

生產:

<tag>&nbsp;</tag>