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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With