Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的Url解码UTF-8_Python_Encoding_Utf 8_Urldecode - Fatal编程技术网

Python中的Url解码UTF-8

Python中的Url解码UTF-8,python,encoding,utf-8,urldecode,Python,Encoding,Utf 8,Urldecode,作为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 对于Python2.7中的这个例子:example.com?title==Пааааааааа+зааа1072 url=urllib.unquote(url.encode(“utf8”)返回了一些非常丑陋的东西 仍

作为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
对于Python2.7中的这个例子:
example.com?title==Пааааааааа+зааа1072

url=urllib.unquote(url.encode(“utf8”)
返回了一些非常丑陋的东西


仍然没有解决方案,非常感谢您的帮助。

数据是通过URL引用转义的UTF-8编码字节,因此您希望解码,它处理从百分比编码数据到UTF-8字节再到文本的解码,透明:

from urllib.parse import unquote

url = unquote(url)
演示:

Python2等价,但它返回一个bytestring,因此您必须手动解码:

from urllib import unquote

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

如果您使用的是Python 3,那么可以使用

给出:

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

您还可以通过
请求
库获得预期结果:

import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")
输出:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip

如果您已经在使用
请求
,而没有使用其他库来执行此作业,则可能会很方便。

那么为什么字符串中还保留+字符?我以为%2B是+字符,+文字在解码过程中被删除了?@Rawrgulmuffins
+
是中的一个空格;您可以使用
urllib.parse.parse_qs()
来解析它,或者使用
urllib.parse.unquote_plus()
。但是它们应该只出现在查询字符串中,而不是URL的其余部分。在一般情况下,URL的尾部只是一个cookie。您无法知道服务器使用哪个本地字符集编码,甚至无法知道URL是否编码字符串或完全不同的内容。(当然,许多URL确实对人类可读的字符串进行编码;而且通常,您可以很容易地猜测编码。但在一般情况下或完全自动地进行编码是不可能的。)在python3.8上使用这种方法并获取dict而不是查询字符串也适用于Python2。
import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")
$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip