Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python encode url with special characters

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?

like image 728
Bob Avatar asked Jul 25 '14 11:07

Bob


People also ask

How do you pass special characters in a URL in Python?

s = urllib2. quote(s) # URL encode. # Now "s" is encoded the way you need it. It works!

How do I encode a URL in Python?

You can encode multiple parameters at once using urllib. parse. urlencode() function. This is a convenience function which takes a dictionary of key value pairs or a sequence of two-element tuples and uses the quote_plus() function to encode every value.

Does Python requests URL encode?

In Python, we can URL encode a query string using the urlib. parse module, which further contains a function urlencode() for encoding the query string in URL.


1 Answers

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.
like image 101
kay Avatar answered Sep 28 '22 20:09

kay