1. 程式人生 > >urllib,url中連結包含漢字怎麼處理

urllib,url中連結包含漢字怎麼處理

使用urllib中的quote,和unquote方法將漢字編碼成gbk(2個百分號對應一個漢字)或者utf8(3個百分號對應一個漢字)

注意用%加密漢字時,漢字不能是Unicode編碼格式,否則會報錯(解決辦法:把Unicode編碼的中文轉換成str格式----->另一篇部落格短文有)

>>> import sys,urllib
>>> s = '漢字'
>>> type(s)
<type 'str'>
>>> s
'\xba\xba\xd7\xd6'
>>> s1 = u'漢字'
>>> type(s1) <type 'unicode'> >>> s1 u'\u6c49\u5b57'

 

>>> urllib.quote(s.decode(sys.stdin.encoding).encode('gbk'))
'%BA%BA%D7%D6'
>>> urllib.quote(s1.decode(sys.stdin.encoding).encode('gbk'))

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    urllib.quote(s1.decode(sys.stdin.encoding).encode('gbk'))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

  

 

>>> urllib.quote(s)
'%BA%BA%D7%D6'
>>> urllib.quote(s1)

Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    urllib.quote(s1)
  File "D:\Python27\lib\urllib.py", line 1298, in quote
    return ''.join(map(quoter, s))
KeyError: u'\u6c49'