python - Python中的Url解码UTF-8

标签 python encoding utf-8 urldecode

在 Python 2.7 中,给定一个类似于 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 的 URL,如何将其解码为预期结果,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')

关于python - Python中的Url解码UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21405676/

相关文章:

python - : Python, ctypes.windll.user32.SystemParametersInfoA 中的参数是什么?

java - 稀疏数据的离散和连续分类器

encoding - 如何读取 DAF( double 组文件) "transfer"文件?

jquery - 使用MVC3的HTML编码和解码

mysql - MySQL 中的 Latin1_swedish_ci 编码

python - unicode 和 python 请求发生了一些有趣的事情

string - 为什么在Julia中不建议对UTF8字符串进行索引?

python - 印地语到英语音译

python - python 中的动态模块加载

javascript - JavaScript 方法中 GrailsElements 的编码