Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url decode UTF-8 in Python

I have spent plenty of time as far as I am newbie in Python.
How could I ever decode such a URL:

example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0 

to this one in python 2.7: example.com?title==правовая+защита

url=urllib.unquote(url.encode("utf8")) is returning something very ugly.

Still no solution, any help is appreciated.

like image 233
swordholder Avatar asked May 15 '13 13:05

swordholder


People also ask

What is decode (' UTF-8 ') in Python?

Encoding refers to encoding a string using an encoding scheme such as UTF-8 . Decoding refers to converting an encoded string from one encoding to another encoding scheme.

How do I remove 20 from a URL in Python?

replace('%20+', '') will replace '%20+' with empty string.


1 Answers

The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote(), which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:

from urllib.parse import unquote  url = unquote(url) 

Demo:

>>> from urllib.parse import unquote >>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0' >>> unquote(url) 'example.com?title=правовая+защита' 

The Python 2 equivalent is urllib.unquote(), but this returns a bytestring, so you'd have to decode manually:

from urllib import unquote  url = unquote(url).decode('utf8') 
like image 187
Martijn Pieters Avatar answered Sep 25 '22 17:09

Martijn Pieters