URL encoding in python

后端 未结 3 1457
余生分开走
余生分开走 2020-12-08 02:53

Is there a simple method I\'m missing in urllib or other library for this task? URL encoding replaces unsafe ASCII characters with a \"%\" followed by two hexa

3条回答
  •  無奈伤痛
    2020-12-08 03:50

    Keep in mind that both urllib.quote and urllib.quote_plus throw an error if an input is a unicode string:

    s = u'\u2013'
    urllib.quote(s)
    
    Traceback (most recent call last):
      File "", line 1, in 
      File "C:\Python27\lib\urllib.py", line 1303, in quote
        return ''.join(map(quoter, s))
    KeyError: u'\u2013'
    

    As answered here on SO, one has to use 'UTF-8' explicitly:

    urllib.quote(s.encode('utf-8'))
    

提交回复
热议问题