python - 求助为什么 linux 的编码这么难搞?
伊谢尔伦
伊谢尔伦 2017-04-17 17:59:07
[Python讨论组]

coding=utf-8 import re import urllib.request html = urllib.request.urlopen("http://study.163.com/").read().decode('utf-8') print(type(html)) print(html)

报错 UnicodeEncodeError: 'ascii' codec can't encode characters in position 595-599: ordinal not in range(128) 如果不出现中文可以输出,出现中文就报错, windows 就没有这个问题。 请问下如何解决? 谷歌能搜的搜了。。

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(4)
阿神

是你的用的编辑器的问题吧,我在atom里面执行的时候会出现这个错误,是因为编辑器的输出编码问题,而在terminal则没有这个问题

PHPz

decode('utf-8') 前加encode('gbk') 即可

迷茫

源编码不匹配的问题

import urllib2
import chardet

response_body=urllib2.urlopen("http://study.163.com/").read()
print response_body.decode((chardet.detect(response_body))['encoding']).encode('utf-8')

高洛峰

haofly说的可能是对的,在控制台不应该会出现这个问题。因为linux下控制台编码是utf-8,而你的代码在收到网页内容后已经将代码decode为unicode了,控制台输出时会按utf-8对unicode进行编码输出。

针对你的这种情况,有两种解决方案,一种是输出时直接输出str而不是unicode。

import urllib2
html = urllib2.urlopen('http://study.163.com').read()
print type(html)
print html

另一种是彻底重载str<->unicode转换时使用的编码方案:

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

import urllib2
html = urllib2.urlopen('http://study.163.com').read().decode('utf-8')
print type(html)
print html
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号