If you are trying to implement to code from web2py url validator, you will notice that you have added and indent to the else where none is needed. White space is important in python. The code that was given in my previous answer is correct, you have just copied it incorrectly. Your code should read like this (the same as my previous answer):
from urllib2 import Request, urlopen, URLError
url = raw_input('enter something')
req = Request(url)
try:
response = urlopen(req)
except URLError, e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
else:
print 'URL is good!'
The else clause is part of the try except not part of the exception test. Basically if an exception is not thrown, the url is valid. The following code gives you this result if you enter http://www.google.com
python test.py
enter somethinghttp://www.google.com
URL is good!
If you enter http://www.google.com/bad you get:
python test.py
enter somethinghttp://www.google.com/bad
The server couldn't fulfill the request.
Error code: 404