在尝试了几种方法之后,总结一下,这就是我的方法。 以下是从解析的HTML字符串中避免/删除\ xa0字符的两种方法。
假设我们的原始html如下:
raw_html = '
Dear Parent,
This is a test message, kindly ignore it.
Thanks
'所以让我们尝试清理这个HTML字符串:
from bs4 import BeautifulSoup
raw_html = '
Dear Parent,
This is a test message, kindly ignore it.
Thanks
'text_string = BeautifulSoup(raw_html, "lxml").text
print text_string
#u'Dear Parent,\xa0This is a test message,\xa0kindly ignore it.\xa0Thanks'
上面的代码在字符串中生成这些字符\ xa0。 要正确删除它们,我们可以使用两种方法。
方法#1(推荐):第一个是BeautifulSoup的get_text方法,strip参数为True所以我们的代码变成:
clean_text = BeautifulSoup(raw_html, "lxml").get_text(strip=True)
print clean_text
# Dear Parent,This is a test message,kindly ignore it.Thanks
方法#2:另一种选择是使用python的库unicodedata
import unicodedata
text_string = BeautifulSoup(raw_html, "lxml").text
clean_text = unicodedata.normalize("NFKD",text_string)
print clean_text
# u'Dear Parent,This is a test message,kindly ignore it.Thanks'
我还在这个博客上详细介绍了这些方法,您可能需要参考这些方法。