
字符串在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编码。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 | #!/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
|
如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断,
isinstance(s, unicode)#用来判断是否为unicode。
最终可靠代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/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自学网。