python解码后乱码的原因是什么?
发布时间:2026-03-22 22:14:58

Python中字符串的表示是unicode编码。编码转换时,通常需要以unicode为中间编码,即首先解码其他编码的字符串(decode)成unicode,然后从unicode编码(encode)另一种编码。
decode的作用是将其他编码的字符串转换为unicode编码,如str1.decode(gb2312)表示将gb2312编码的字符串str1转换为unicode编码。
encode的作用是将unicode编码转换为其他编码的字符串,如str2.encode(‘utf-8)表示将unicode编码的字符串str2转换为utf-8编码。
代码如下:
#!/usr/bin/envpython
#-*-coding:utf-8-*-
#author:xulinjietime:2017/10/22
importurliblib
request=urllib2.Request(r'http://nhxy.zjxu.edu.cn/')
RES=urllib2.urlopen(request).read()
RES=RES.decode('gb2312').encode('utf-8')//解决乱码
wfile=open(r'./1.html',r'wb')
wfile.write(RES)
wfile.close()
printRES假如一个字符串已经是unicode了,再解码就会出错,所以通常要判断其编码方法是否是unicode,
isinstance(s, unicode)#用于判断unicode是否为unicode。
最终可靠代码:
#!/usr/bin/envpython
#-*-coding:utf-8-*-
#author:xulinjietime:2017/10/22
importurliblib
request=urllib2.Request(r'http://nhxy.zjxu.edu.cn/')
RES=urllib2.urlopen(request).read()
ifisinstance(RES,unicode):
RES=RES.encode('utf-8')
else:
RES=RES.decode('gb2312').encode('utf-8')
wfile=open(r'./1.html',r'wb')
wfile.write(RES)
wfile.close()
printRES请关注Python自学网了解更多Python知识。
