Python用特殊字符编码url

2024-06-07 04:40:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用特殊字符编码URL。在我的例子中是:š, ä, õ, æ, ø(它不是一个有限列表)。

urllib2.quote(symbol)给出了非常奇怪的结果,这是不正确的。这些符号还能怎么编码呢?


Tags: url编码列表符号urllib2symbol例子quote
1条回答
网友
1楼 · 发布于 2024-06-07 04:40:29

urllib2.quote("Grønlandsleiret, Oslo, Norway") gives a %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.

相关问题 更多 >