Python urllib2 URLError HTTP status code.

前端 未结 2 1969
再見小時候
再見小時候 2021-02-03 20:45

I want to grab the HTTP status code once it raises a URLError exception:

I tried this but didn\'t help:

except URLError, e:
    logger.warning( \'It see         


        
2条回答
  •  失恋的感觉
    2021-02-03 21:16

    You shouldn't check for a status code after catching URLError, since that exception can be raised in situations where there's no HTTP status code available, for example when you're getting connection refused errors.

    Use HTTPError to check for HTTP specific errors, and then use URLError to check for other problems:

    try:
        urllib2.urlopen(url)
    except urllib2.HTTPError, e:
        print e.code
    except urllib2.URLError, e:
        print e.args
    

    Of course, you'll probably want to do something more clever than just printing the error codes, but you get the idea.

提交回复
热议问题