Search code examples
pythonurllib2

If condition on error message after response.read


response = urllib2.urlopen("http://example.com/Hi")
html = response.read()

Is it possible that when the above code is run while the Hi directory has been removed (or the server is not available), instead of crashing, an action like below is done?

if html==404:
    print("No response")

Solution

  • You can use the requests module
    simply after getting the request, check the status code

        import requests
        r = requests.get('http://httpbin.org/status/404')
        print(r.status_code) # the output is the int: 404
    

    if everything is ok

    if r.ok:
        # cool stuff :)
    

    if page not found:

    if r.status_code == 404:
        # so sad :(
    

    Read more:
    https://realpython.com/python-requests/

    Requests -- how to tell if you're getting a 404