BUG URLLIB2
John Hunter
jdhunter at nitace.bsd.uchicago.edu
Thu Nov 14 20:02:55 EST 2002
>>>>> "bart" == bart <e_viola at libero.it> writes:
bart> I'm an italian student and my problem consists about
bart> urllib2; urlopen function, sometimes, give me old (and
bart> inexactly) url because the site has moved in a new location
bart> but urlopen doesn't undestand it and return 403 error
bart> FORBIDDEN.
I don't think you can describe this as a bug; it's a feature! python
provides exceptions to handle, well, exceptional circumstances, such
as trying to access a web site that you are forbidden to access. When
this happens, an 'exception' is raised, and there is a mechanism to
handle the exception.
A simple example
class MyClass:
def __init__(self, x):
self.x = x
c = MyClass(1)
print c.x # ok
print c.y # illegal, an AttributeError is raised
In order to try something that might raise an exception, enclose it in
try/except blocks
try: print c.x
except AttributeError: 'There is no attribute x'
try: print c.y
except AttributeError: 'There is no attribute y'
There are lots of kinds of kinds of exceptions, and individual modules can
create their own. Suppose we wanted to divide some number by y, but
y equals 0
y = 1
print 2/y # this is ok
y = 0
print 2/y # this is not so good, and will raise a ZeroDivisionError
You can define default behavior if someone tries to divide by zero by
handling the exception
try: print 2/y
except ZeroDivisionError: print 'You are about to explode!'
Now, to make a long story short, you need to handle the
urllib2.HTTPError exception in your example
try: con=urllib2.urlopen('http://www.google.it/search')
except urllib2.HTTPError: print "Can't read the web site, try again!"
For a tutorial introduction to exceptions, see
http://python.org/doc/current/tut/node10.html
For future reference: python is a mature language and it is a rare
experience indeed to find a bug. User error is far more common.
Also, cross posting the question to many USENET groups and mailing
lists is generally frowned upon. If it is a python question and you
post to this group alone, chances are good that you'll get a reply
within the hour, usually much sooner.
Good luck!
John Hunter
More information about the Python-list
mailing list