python 2.7 中的等效 urllib.parse.unquote()

Equivalent urllib.parse.unquote() in python 2.7

我在 python 2.7 中导入 urlparse 而不是 urllib.parse 但得到 AttributeError : 'function' 对象没有属性 'unquote'

File "./URLDefenseDecode2.py", line 40, in decodev2
    htmlencodedurl = urlparse.unquote(urlencodedurl)

urllib.parse.unquote() 在 python 2.7 中的等价物是什么?

在Python2.7中,unquote直接在urllib中:urllib.unquote(string)

Python3urllib.parse.unquote的语义与Python2urllib.unqote的语义不同,尤其是在处理non-ascii字符串时。

以下代码应该允许您始终使用 Python 3 的较新语义,最终当您不再需要支持 Python 2 时,您可以删除它。

try:
    from urllib.parse import unquote
except ImportError:
    from urllib import unquote as stdlib_unquote

    # polyfill. This behaves the same as urllib.parse.unquote on Python 3
    def unquote(string, encoding='utf-8', errors='replace'):
        if isinstance(string, bytes):
            raise TypeError("a bytes-like object is required, not '{}'".format(type(string)))

        return stdlib_unquote(string.encode(encoding)).decode(encoding, errors=errors)