Url在Python中解码UTF-8

swo*_*der 227 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
Run Code Online (Sandbox Code Playgroud)

在python 2.7中的这个: example.com?title==????????+??????

url=urllib.unquote(url.encode("utf8")) 正在回归一些非常难看的东西.

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

Mar*_*ers 358

数据是使用URL引用转义的UTF-8编码字节,因此您要解码:

from urllib.parse import unquote

url = unquote(url)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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=????????+??????'
Run Code Online (Sandbox Code Playgroud)

相当于Python 3 urllib.parse.unquote(),默认情况下为您处理解码:

from urllib import unquote

url = unquote(url).decode('utf8')
Run Code Online (Sandbox Code Playgroud)

  • @Rawrgulmuffins` +`是[`x-www-form-urlencoded` data]中的一个空格(http://en.m.wikipedia.org/wiki/Application/x-www-form-urlencoded#The_application.2Fx- WWW的形式urlencoded_type); 你可以使用`urllib.parse_qs`来解析它,或者使用`urllib.unquote_plus()`.但它们应该只出现在查询字符串中,而不是URL的其余部分. (4认同)
  • 那么为什么+字符会留在字符串中呢?我认为 %2B 是 + 字符,并且 + 文字在解码过程中被删除了? (3认同)

pav*_*van 136

如果您使用的是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)
Run Code Online (Sandbox Code Playgroud)

得到:

'example.com?title=????????+??????'
Run Code Online (Sandbox Code Playgroud)


iva*_*ncz 11

您也可以使用requests库实现预期结果:

import requests

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

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")
Run Code Online (Sandbox Code Playgroud)

输出:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip
Run Code Online (Sandbox Code Playgroud)

如果您已经在使用requests,而无需为此工作使用其他库,则可能会很方便。