python(22)总结下最近遇到的编码问题

最近爬取,或者解析网页是总是遇到编码问题(我的版本:python2.7)

一、常见异常:UnicodeEncodeError: 'ascii' codec can't encode character u'\xb4' in position 0: ordinal not in range(128)

常见解决方案:在代码头添加如下文件

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

有时也会遇到字符转换的问题:

>>> str(u'')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u6211' in position 0: ordinal not in range(128)

解决方法如下:

>>> str(u''.encode('utf-8'))
'\xe6\x88\x91'

二、在爬取网页进行解析的时候,遇到中文需要存储的,一般要先看一下中文是什么格式的,如果是unicode则需要进行转码

xx = xxx.encode('utf-8')
f.write(xx)

 

注:以上解决方案有所借鉴其他博友,未能找到源博

posted on 2016-08-17 15:18  细雨微光  阅读(455)  评论(0编辑  收藏  举报