0

This is part of my code in python. I want to check the error message and if HTTPError() then I want to add the host to the file ok.txt. But it doesn't work. what is the problem here?

except urllib2.URLError, e:
        print '%-15s\t%15r' % (url.strip(), e)
        if e == 'HTTPError()':
            OK.write('%-15s' % (url.strip()) + '\n')
            OK.flush()

When I run whole script the output is something like this:

http://a.com        HTTPError()
http://b.com    URLError(timeout('timed out',),)
http://c.com    URLError(timeout('timed out',),)
http://d.com    URLError(error(111, 'Connection refused'),)
http://e.com           200

1 Answer 1

3

Use isinstance() to check whether or not your error is of type HTTPError:

except urllib2.URLError as e: # use the "as e" instead of the old style comma delimitation.
    print '%-15s\t%15r' % (url.strip(), e)
    if isinstance(e, HTTPError):
        OK.write('%-15s' % (url.strip()) + '\n')
        OK.flush()
Sign up to request clarification or add additional context in comments.

2 Comments

Because HTTPError() calls the exception class. In effect it creates a new exception object but does not raise it. HTTPError is the type, which you can check against.
Thank you... I am checking your solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.