2011-02-07 103 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部在输出略有差异。

希望这节省了别人花时间弄清楚这一点!