Python urllib urlencode problem with æøå

人盡茶涼 提交于 2019-12-18 12:37:54

问题


How can I urlencode a string with special chars æøå?

ex.

urllib.urlencode('http://www.test.com/q=testæøå')

I get this error :(..

not a valid non-string sequence or mapping object


回答1:


You should pass dictionary to urlencode, not a string. See the correct example below:

from urllib import urlencode
print 'http://www.test.com/?' + urlencode({'q': 'testæøå'})



回答2:


urlencode is intended to take a dictionary, for example:

>>> q= u'\xe6\xf8\xe5' # u'æøå'
>>> params= {'q': q.encode('utf-8')}
>>> 'http://www.test.com/?'+urllib.urlencode(params)
'http://www.test.com/?q=%C3%A6%C3%B8%C3%A5'

If you just want to URL-encode a single string, the function you're looking for is quote:

>>> 'http://www.test.com/?q='+urllib.quote(q.encode('utf-8'))
'http://www.test.com/?q=%C3%A6%C3%B8%C3%A5'

I'm guessing UTF-8 is the right encoding (it should be, for modern sites). If what you actually want ?q=%E6%F8%E5, then the encoding you want is probably cp1252 (similar to iso-8859-1).



来源:https://stackoverflow.com/questions/3996974/python-urllib-urlencode-problem-with-%c3%a6%c3%b8%c3%a5

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