如何正确url编码重音?

时间:2011-02-07 17:17:23

标签: python escaping urllib2 urlencode

我需要对外来名称进行url编码,例如“Misère”。

当我这样做时:

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'

我做错了什么?

2 个答案:

答案 0 :(得分:12)

尝试:

urllib2.quote(s.encode('utf8'))

答案 1 :(得分:0)

对@苏妍倩的回答略有改进,就是在方法调用中加入安全字符。默认情况下,urllib2.quote()仅包含/ _ - .作为安全字符,这意味着将转换:之类的字符,呈现网址无用的。

例如:

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部分输出略有不同。

希望这可以节省别人花时间解决这个问题的时间!

相关问题