Reputation: 3596
I import urlparse instead of urllib.parse in python 2.7 but getting AttributeError: 'function' object has no attribute 'unquote'
File "./URLDefenseDecode2.py", line 40, in decodev2
htmlencodedurl = urlparse.unquote(urlencodedurl)
What is the equivalent urllib.parse.unquote() in python 2.7 ?
Upvotes: 3
Views: 7820
Reputation: 8469
The semantics of Python 3 urllib.parse.unquote
are not the same as Python 2 urllib.unqote
, especially when dealing with non-ascii strings.
The following code should allow you to always use the newer semantics of Python 3 and eventually you can just remove it, when you no longer need to support 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)
Upvotes: 3
Reputation: 18106
In Python 2.7, unquote is directly in urllib: urllib.unquote(string)
Upvotes: 5