我希望能够用特殊字符对URL进行编码。 在我的情况下,它们是:š、ä、õ、æ、ø
(这不是有限列表)。
urllib2.quote(symbol)
会给出非常奇怪且不正确的结果。 还有什么其他方式可以对这些符号进行编码呢?
urllib2.quote("Grønlandsleiret, Oslo, Norway")
会得到%27Gr%B8nlandsleiret%2C%20Oslo%2C%20Norway%27
那就显式地使用UTF-8:
urllib2.quote(u"Grønlandsleiret, Oslo, Norway".encode('UTF-8'))
请始终在文件中声明编码方式。详见PEP 0263。
非UTF-8字符串需要先解码再进行编码:
# You've got a str "s".
s = s.decode('latin-1') # (or what the encoding might be …)
# Now "s" is a unicode object.
s = s.encode('utf-8') # Encode as UTF-8 string.
# Now "s" is a str again.
s = urllib2.quote(s) # URL encode.
# Now "s" is encoded the way you need it.
urllib2.quote('ä') == '%C3%A4'
。 - Kijewskiurllib2.quote("Grønlandsleiret, Oslo, Norway")
对我来说返回的是'Gr%C3%B8nlandsleiret%2C%20Oslo%2C%20Norway'
。访问相应的URL会显示有效响应:https://maps.googleapis.com/maps/api/geocode/json?address=Gr%C3%B8nlandsleiret%2C%20Oslo%2C%20Norway。 - falsetru