2016年7月10日 星期日

python url encode/decode

環境是 python 2.7 下:

import urllib

#測試初始 unicode 字串物件
strUnicode = u"test data"

#字串型態為 UNICODE
type(strUnicode)
<type 'unicode'>

#開始 url encode,先將 unicode 編碼為 utf-8,再 url encode (quote),得到 utf-8 字串物件
strResult = urllib.quote(strUnicode.encode("utf-8"))
type(srtResult)
<type 'str'>

#開始 url decode,將上面的結果進行 url decode (unquote),再解碼回 unicode 字串物件
 strResult = urllib.unquote(urllib.quote(u_str.encode("utf-8"))).decode("utf-8")
type(srtResult)
<type 'unicode'>

沒有留言: