标签归档:urldecode

网址在Python中解码UTF-8

问题:网址在Python中解码UTF-8

就我是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.


回答 0

该数据是UTF-8编码的字节逃脱URL引用,所以要解码,用urllib.parse.unquote(),它处理从百分比编码数据进行解码,以UTF-8字节,然后于文字,透明:

from urllib.parse import unquote

url = unquote(url)

演示:

>>> 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=правовая+защита'

Python 2的等效项是urllib.unquote(),但是它返回一个字节串,因此您必须手动进行解码:

from urllib import unquote

url = unquote(url).decode('utf8')

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')

回答 1

如果您使用的是Python 3,则可以使用 urllib.parse

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"""

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

给出:

'example.com?title=правовая+защита'

If you are using Python 3, you can use urllib.parse

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"""

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

gives:

'example.com?title=правовая+защита'