Possible Duplicate:
web2py url validator
would you help me on this code?
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!'
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):
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
If you enter http://www.google.com/bad you get: