简体   繁体   English

Python使用特殊字符编码url

[英]Python encode url with special characters

I want to encode URL with special characters. 我想用特殊字符编码URL。 In my case it is: š, ä, õ, æ, ø (it is not a finite list). 在我的情况下它是: š, ä, õ, æ, ø (它不是有限的列表)。

urllib2.quote(symbol) gives very strange result, which is not correct. urllib2.quote(symbol)给出了非常奇怪的结果,这是不正确的。 How else these symbols can be encoded? 这些符号怎么可以编码?

urllib2.quote("Grønlandsleiret, Oslo, Norway") gives a %27Gr%B8nlandsleiret%2C%20Oslo%2C%20Norway%27 urllib2.quote("Grønlandsleiret, Oslo, Norway")给出%27Gr%B8nlandsleiret%2C%20Oslo%2C%20Norway%27

Use UTF-8 explicitly then: 然后明确使用UTF-8:

urllib2.quote(u"Grønlandsleiret, Oslo, Norway".encode('UTF-8'))

And always state the encoding in your file. 并始终在您的文件中声明编码。 See PEP 0263 . PEP 0263


A non-UTF-8 string needs to be decode first, then encoded: 需要首先解码非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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM