掃二維碼與項目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
字符串在python內(nèi)部的表示是unicode編碼,在做編碼轉(zhuǎn)換時,通常需要以unicode作為中間編碼,即先將其他編碼的字符串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。

容縣ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書合作)期待與您的合作!
decode的作用是將其他編碼的字符串轉(zhuǎn)換成unicode編碼,如str1.decode(‘gb2312’),表示將gb2312編碼的字符串str1轉(zhuǎn)換成unicode編碼。
encode的作用是將unicode編碼轉(zhuǎn)換成其他編碼的字符串,如str2.encode(‘utf-8’),表示將unicode編碼的字符串str2轉(zhuǎn)換成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如果一個字符串已經(jīng)是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 
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流