Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: name 'urllib2' is not defined [closed]

I am currently building a webscraper and I need to catch url exceptions. My code sample is the one below.

from urllib2 import urlopen

Try:
  //some code


Except urllib2.HTTPError:
  pass
like image 635
user3073498 Avatar asked Apr 16 '14 13:04

user3073498


1 Answers

You only imported the name urlopen, not the urllib2 module itself.

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():

 import urllib2

 try:
     # ...
     response = urllib2.urlopen(...)
     # ...
 except urllib2.HTTPError:
     pass
like image 165
Martijn Pieters Avatar answered Oct 04 '22 17:10

Martijn Pieters