Python 处理特殊字符的URL编码

11 投票
1 回答
27048 浏览
提问于 2025-04-18 14:44

我想把网址中的特殊字符进行编码。在我的情况下,这些字符是:š, ä, õ, æ, ø(这不是一个固定的列表)。

urllib2.quote(symbol) 的结果很奇怪,并不正确。还有什么其他方法可以对这些符号进行编码呢?

1 个回答

15

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.

撰写回答