Python NameError: 名称 'urllib2' 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23110566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NameError: name 'urllib2' is not defined
提问by user3073498
I am currently building a webscrapper and I need to catch url exceptions. My code sample is the one below.
我目前正在构建一个 webscrapper,我需要捕获 url 异常。我的代码示例如下。
from urllib2 import urlopen
Try:
//some code
Except urllib2.HTTPError:
pass
回答by Martijn Pieters
You only imported the name urlopen
, not the urllib2
module itself.
您只导入了 name urlopen
,而不是urllib2
模块本身。
Import the exception too and refer to it directly:
也导入异常,直接引用:
from urllib2 import urlopen, HTTPError
try:
# ...
except HTTPError:
pass
Alternatively, import just the module, but then also use urllib2.urlopen()
:
或者,只导入模块,然后也使用urllib2.urlopen()
:
import urllib2
try:
# ...
response = urllib2.urlopen(...)
# ...
except urllib2.HTTPError:
pass