Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
The Python "NameError: name 'urllib' is not defined" occurs when we use the
urllib
module without importing it first. To solve the error, import the
urllib
module before using it - import urllib.request
.
Here is an example of how the error occurs.
# ⛔️ NameError: name 'urllib' is not defined with urllib.request.urlopen('http://www.python.org/') as f: print(f.read())
To solve the error, we have to import the urllib module.
import urllib.request with urllib.request.urlopen('http://www.python.org/') as f: print(f.read())
The example shows how to import the urllib.request
module which is what you'll
most often use.
You can use the same approach to import urllib.error
or urllib.parse
.
import urllib.request import urllib.error import urllib.parse with urllib.request.urlopen('http://www.python.org/') as f: print(f.read()) pass params = urllib.parse.urlencode({'a': 1, 'b': 2, 'c': 3}) print(params)
Even though the urllib
module is in the Python standard library, we still have
to import it before using it.
u
when importing urllib
because module names are case-sensitive.Also, make sure you haven't imported urllib
in a nested scope, e.g. a
function. Import the module at the top level to be able to use it throughout
your code.
An alternative to importing the entire urllib.request
, urllib.parse
or
urllib.error
modules is to import only the functions that our code uses.
from urllib.request import urlopen from urllib.parse import urlencode with urlopen('http://www.python.org/') as f: print(f.read()) params = urlencode({'a': 1, 'b': 2, 'c': 3}) print(params)
The example shows how to import only the urlopen
function from the
urllib.request
module and the urlencode
function from the urllib.parse
module.
Instead of accessing the members on the module, e.g. urllib.request.urlopen()
,
we now access them directly.
This should be your preferred approach because it makes your code easier to read.
import urllib.request
, it is much harder to see which functions from the urllib.request
module are being used in the file.Conversely, when we import specific functions, it is much easier to see which
functions from the urllib.request
module are being used.
You can read more about the sub-modules the urllib
module provides by visiting
the official docs.