如何正确进行URL编码中的重音符号?

7 投票
2 回答
4380 浏览
提问于 2025-04-16 11:23

我需要对一些外文名字进行网址编码,比如“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

对@苏妍倩的回答稍微改进一下,可以在方法调用中加入安全字符。默认情况下,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部分输出有一点小差别。

希望这能帮到其他人,省去我花时间搞明白的麻烦!

13

试试这个:

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

撰写回答