NameError:名称“urllib”未在 Python 中定义
NameError: name ‘urllib’ is not defined in Python
Python“NameError: name ‘urllib’ is not defined”发生在我们使用
urllib
模块而不先导入它时。要解决错误,请
urllib
在使用之前导入模块 – import urllib.request
。
下面是错误如何发生的示例。
# ⛔️ NameError: name 'urllib' is not defined with urllib.request.urlopen('http://www.python.org/') as f: print(f.read())
为了解决这个错误,我们必须导入
urllib模块。
import urllib.request with urllib.request.urlopen('http://www.python.org/') as f: print(f.read())
该示例显示了如何导入urllib.request
您最常使用的模块。
您可以使用相同的方法导入urllib.error
或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)
即使该urllib
模块在 Python 标准库中,我们仍然需要在使用前导入它。
u
确保在导入时没有使用大写字母,因为模块名称区分大小写。 urllib
另外,请确保您没有导入urllib
嵌套范围,例如函数。在顶层导入模块,以便能够在整个代码中使用它。
导入整个 或 模块的替代方法urllib.request
是urllib.parse
仅
urllib.error
导入我们的代码使用的函数。
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)
该示例显示了如何仅导入模块中的函数和模块中urlopen
的
函数
。urllib.request
urlencode
urllib.parse
例如urllib.request.urlopen()
,我们现在直接访问它们,而不是访问模块上的成员。
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.
Conclusion #
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
.