尝试几种方法后,总结它,这是我做到了。以下是避免/从解析的HTML字符串中移除\ xa0个字符的两种方法。
假设我们有原始的HTML如下:
raw_html = '<p>Dear Parent, </p><p><span style="font-size: 1rem;">This is a test message, </span><span style="font-size: 1rem;">kindly ignore it. </span></p><p><span style="font-size: 1rem;">Thanks</span></p>'
所以让我们尝试清除该HTML字符串:
from bs4 import BeautifulSoup
raw_html = '<p>Dear Parent, </p><p><span style="font-size: 1rem;">This is a test message, </span><span style="font-size: 1rem;">kindly ignore it. </span></p><p><span style="font-size: 1rem;">Thanks</span></p>'
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方法与条参数作为真 因此,我们的代码变为:
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'
我也详细介绍了这些方法on this blog你可能想参考。
'str.replace('\ xa0','')'? –
已经尝试过,'ascii'编解码器无法解码位置0中的字节0xa0:序号不在范围内(128) – zhuyxn
包含Unicode。使用'''''而不是'''s。 :-) – jpaugh