Fix - NameError: name 'urllib' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

Fix - NameError: name 'urllib' is not defined in Python #

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.

nameerror name urllib is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ 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.

main.py
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.

main.py
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.

Make sure you haven't used a capital letter 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.

main.py
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.

For example, when we use an import such as 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.