我已经花了很多时间,就像我在Python中的新手一样。 我如何解码这样一个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在python 2.7中的这个: example.com?title==правовая+защита
url=urllib.unquote(url.encode("utf8"))正在返回非常难看的东西。
仍然没有解决方案,任何帮助是赞赏。
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%B0to 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.
最满意答案
数据是通过URL引用转义的UTF-8编码字节,因此您要解码 :
url=urllib.unquote(url).decode('utf8')演示:
>>> import urllib >>> 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' >>> urllib.unquote(url).decode('utf8') u'example.com?title=\u043f\u0440\u0430\u0432\u043e\u0432\u0430\u044f+\u0437\u0430\u0449\u0438\u0442\u0430' >>> print urllib.unquote(url).decode('utf8') example.com?title=правовая+защита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')更多推荐
发布评论