在 Python 中 URL 解码 UTF-8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16566069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:00:19  来源:igfitidea点击:

Url decode UTF-8 in Python

pythonencodingutf-8urldecode

提问by swordholder

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

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

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

到python 2.7中的这个: example.com?title==правовая+защита

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

url=urllib.unquote(url.encode("utf8"))正在返回非常丑陋的东西。

Still no solution, any help is appreciated.

仍然没有解决方案,任何帮助表示赞赏。

采纳答案by Martijn Pieters

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:

数据是使用 URL 引用转义的 UTF-8 编码字节,因此您要解码, with urllib.parse.unquote(),它可以透明地处理从百分比编码数据到 UTF-8 字节然后到文本的解码:

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:

Python 2 的等价物是urllib.unquote(),但这会返回一个字节串,因此您必须手动解码:

from urllib import unquote

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

回答by pavan

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

如果您使用的是 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)

gives:

给出:

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