percent encoding URL with python

后端 未结 1 625
孤城傲影
孤城傲影 2020-12-11 05:22

When I enter a URL into maps.google.com such as https://dl.dropbox.com/u/94943007/file.kml , it will encode this URL into:

https:%2F%2Fdl.dropbox.com%2Fu%2F9         


        
相关标签:
1条回答
  • 2020-12-11 05:35

    Use

    urllib.quote_plus(url, safe=':')
    

    Since you don't want the colon encoded you need to specify that when calling urllib.quote():

    >>> expected = 'https:%2F%2Fdl.dropbox.com%2Fu%2F94943007%2Ffile.kml'
    >>> url = 'https://dl.dropbox.com/u/94943007/file.kml'
    >>> urllib.quote(url, safe=':') == expected
    True
    

    urllib.quote() takes a keyword argument safe that defaults to / and indicates which characters are considered safe and therefore don't need to be encoded. In your first example you used '' which resulted in the slashes being encoded. The unexpected output you pasted below where the slashes weren't encoded probably was from a previous attempt where you didn't set the keyword argument safe at all.

    Overriding the default of '/' and instead excluding the colon with ':' is what finally yields the desired result.

    Edit: Additionally, the API calls for spaces to be encoded as plus signs. Therefore urllib.quote_plus() should be used (whose keyword argument safe doesn't default to '/').

    0 讨论(0)
提交回复
热议问题