python - 网址在 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")) 返回的东西非常丑陋。

仍然没有解决方案,感谢任何帮助。

最佳答案

数据是使用 URL 引用转义的 UTF-8 编码字节,因此您想要解码,使用 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')

https://stackoverflow.com/questions/16566069/

相关文章:

python - 在 Python 中创建一个空列表

linux - 删除目录的符号链接(symbolic link)

python - 用一个空格替换非 ASCII 字符

linux - 在 Bash 中循环文件的内容

python - 如何禁用 Pylint 警告?

c - 为什么 C 预处理器将单词 "linux"解释为常量 "1"?

linux - 将多个 PDF 文件合并/转换为一个 PDF

python - 子进程中 'shell=True'的实际含义

python - pip 在哪里安装它的包?

linux - 如何将包含文件的文件夹复制到 Unix/Linux 中的另一个文件夹?