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 ?标题= =правовая+защита
url=urllib.unquote(url.encode("utf8"))
is returning something very ugly.
url=urllib.unquote(url.encode("utf8"))返回非常丑陋的东西。
Still no solution, any help is appreciated.
仍然没有解决办法,任何帮助都是值得感激的。
2 个解决方案
#1
247
The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode:
数据是UTF-8编码的字节通过URL引用转义,所以你要解码:
url = urllib.unquote(url).decode('utf8')
Demo:
演示:
>>> import urllib
>>> 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'
>>> urllib.unquote(url).decode('utf8')
u'example.com?title=\u043f\u0440\u0430\u0432\u043e\u0432\u0430\u044f+\u0437\u0430\u0449\u0438\u0442\u0430'
>>> print urllib.unquote(url).decode('utf8')
example.com?title=правовая+защита
The Python 3 equivalent is urllib.parse.unquote()
, which by default handles decoding for you:
Python 3的等效项是urllib.parse.unquote(),它默认为您处理译码:
from urllib.parse import unquote
url = unquote(url)
#2
101
If you are using Python 3, you can use urllib.parse
如果您使用的是python3,您可以使用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=правовая+защита'
#1
247
The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode:
数据是UTF-8编码的字节通过URL引用转义,所以你要解码:
url = urllib.unquote(url).decode('utf8')
Demo:
演示:
>>> import urllib
>>> 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'
>>> urllib.unquote(url).decode('utf8')
u'example.com?title=\u043f\u0440\u0430\u0432\u043e\u0432\u0430\u044f+\u0437\u0430\u0449\u0438\u0442\u0430'
>>> print urllib.unquote(url).decode('utf8')
example.com?title=правовая+защита
The Python 3 equivalent is urllib.parse.unquote()
, which by default handles decoding for you:
Python 3的等效项是urllib.parse.unquote(),它默认为您处理译码:
from urllib.parse import unquote
url = unquote(url)
#2
101
If you are using Python 3, you can use urllib.parse
如果您使用的是python3,您可以使用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=правовая+защита'