Python encode url with special characters

无人久伴 提交于 2019-12-10 13:48:50

问题


I want to encode URL with special characters. In my case it is: š, ä, õ, æ, ø (it is not a finite list).

urllib2.quote(symbol) gives very strange result, which is not correct. How else these symbols can be encoded?


回答1:


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

Use UTF-8 explicitly then:

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

And always state the encoding in your file. See PEP 0263.


A non-UTF-8 string needs to be decode first, then encoded:

                           # 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.


来源:https://stackoverflow.com/questions/24954786/python-encode-url-with-special-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!