在Python地址解码UTF-8(Url decode UTF-8 in Python)

2019-09-03 09:00发布

只要我在Python新手我花了大量的时间。
我怎能解码这样的网址:

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"))将返回的东西非常难看。

还是无解,任何帮助表示赞赏。

Answer 1:

该数据是UTF-8编码的字节逃脱URL引用,所以要进行解码

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

Python的3当量是urllib.parse.unquote()它默认把手您解码:

from urllib.parse import unquote

url = unquote(url)


Answer 2:

如果您在使用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=правовая+защита'


文章来源: Url decode UTF-8 in Python