2011-02-07 102 views
6

我需要url編碼外部名稱,如「Misère」。如何正確的URL編碼口音?

當我這樣做:

urllib2.quote(name) 

我得到一個錯誤:

File "/System/Library/Frameworks/Python.framework/Versions/ 
2.5/lib/python2.5/urllib.py", line 1205, in quote 
    res = map(safe_map.__getitem__, s) 
KeyError: u'\xe8' 

我在做什麼錯?

回答

12

嘗試urllib2.quote(s.encode(「utf-8」))

+1

工作,謝謝! – 2011-02-07 17:52:01

0

略有改善爲@蘇妍倩的回答應該包含在方法調用的安全角色。默認情況下,urllib2.quote()僅包含/_-.作爲安全字符,這意味着像:這樣的字符將被轉換,從而使url無效。

例如:

url = https://www.zomato.com/pittsburgh/caffè-damore-catering-pittsburgh 
print urllib2.quote(url.encode('utf-8')) 
>>> https%3A//www.zomato.com/pittsburgh/caff%C3%A8-damore-catering-pittsburgh 

print urllib2.quote(url.encode('utf-8'),':/') 
>>> https:////www.zomato.com/pittsburgh/caff%C3%A8-damore-catering-pittsburgh 

注意到網址的HTTPS部在輸出略有差異。

希望這節省了別人花時間弄清楚這一點!