python print unicode错误bug

在爬虫爬取网页内容遇到的bug

Debug错误提示:UnicodeEncodeError: 'gbk' codec can't encode character u'\xa0' in position 0: illegal multibyte sequence

代码:

response1=urllib2.urlopen(url)
r_doc=response1.read()
soup=BeautifulSoup(r_doc, 'html.parser',from_encoding='utf-8')  

content=soup.find('div',id="content")
doc=content.get_text()
print doc

后来经过验证

print u"中文"

不会报错

但是

print u"\xa0中文"

debug产生错误

\xa0 属于 latin1 (ISO/IEC_8859-1)中的扩展字符集字符,代表空白符nbsp(non-breaking space)
latin1 字符集向下兼容 ASCII ( 0x20~0x7e )。通常我们见到的字符多数是 latin1 的,比如在 MySQL 数据库中。

经过测验 将代码修改为

response1=urllib2.urlopen(url)
r_doc=response1.read()
soup=BeautifulSoup(r_doc, 'html.parser',from_encoding='utf-8')  

content=soup.find('div',id="content")
doc=content.get_text().replace(u"\xa0"," ")
print doc
使用relace 将爬取内容中的\xa0修改为空格,程序成功运行

猜你喜欢

转载自blog.csdn.net/zhuochuyu7096/article/details/79945657