python解码后乱码的原因是什么?

发布时间:2022-06-09 09:39:07 人气:149 作者:多测师

  字符串在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/env python

  # -*- coding:utf-8 -*-

  # author: xulinjie time:2017/10/22

  import urllib2

  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()

  print RES

python解码后乱码的原因是什么?

  如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断,

  isinstance(s, unicode)#用来判断是否为unicode。

  最终可靠代码:

  #!/usr/bin/env python

  # -*- coding:utf-8 -*-

  # author: xulinjie time:2017/10/22

  import urllib2

  request=urllib2.Request(r'http://nhxy.zjxu.edu.cn/')

  RES=urllib2.urlopen(request).read()

  if isinstance(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()

  print RES

  以上内容为大家介绍了Python解码后乱码的原因是什么?希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线