'module' has no attribute 'urlencode'

PythonPython 3.xUrllib

Python Problem Overview


When I try to follow the Python Wiki's example related to URL encoding:

>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()

An error is raised on the second line:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'urlencode'

What am I missing?

Python Solutions


Solution 1 - Python

urllib has been split up in Python 3.

The urllib.urlencode() function is now urllib.parse.urlencode(),

the urllib.urlopen() function is now urllib.request.urlopen().

Solution 2 - Python

import urllib.parse
urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})

Solution 3 - Python

You use the Python 2 docs but write your program in Python 3.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCrollView Question on Stackoverflow
Solution 1 - PythonKevinView Answer on Stackoverflow
Solution 2 - PythonVijay P RView Answer on Stackoverflow
Solution 3 - PythonUserView Answer on Stackoverflow