UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 273: ordinal not in range(128)

今天利用python urllib2去站长之家查询域名的whois,然后出现如下错误:
>>> whois = urllib2.urlopen('http://whois.chinaz.com/qclouds.com.cn')
[quote]>> print (whois.read().decode())
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 273: ordinal not in range(128)
原因分析:
python的str默认是ascii编码,和unicode编码冲突,就会报这个标题错误。
通过搜集网上的资料,自己多次尝试,问题总算是解决了,在代码中加上如下几句即可:
import sys
reload(sys)
sys.setdefaultencoding('utf8')
不知道还有更好的办法吗? 修复后,结果如下: [attach]562[/attach] http://docs.python.org/howto/unicode.html  这个是python的unicode编码API文档,英文好的同学可以看一下,加深理解。 参考资料:https://groups.google.com/forum/#!topic/python-cn/9I73RUUnQPY 

混淆了 python2 里边的 str 和 unicode 数据类型

你需要的是让编码用实际编码而不是 ascii 对需要 str->unicode 的代码,可以在前边写上
import sys
reload(sys)
sys.setdefaultencoding(‘utf8′)
把 str 编码由 ascii 改为 utf8 (或 gb18030) python3 区分了 unicode str 和 byte arrary,并且默认编码不再是 ascii[/quote]

0 个评论

要回复文章请先登录注册