Url在Python中解码UTF

编程入门 行业动态 更新时间:2024-10-28 03:17:41
Url在Python中解码UTF-8(Url decode UTF-8 in Python)

我已经花了很多时间,就像我在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%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.

最满意答案

数据是通过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')

更多推荐

本文发布于:2023-08-05 01:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1426187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Url   Python   UTF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!