2

I am trying to check if a URL to a jpg is real. This code works, returns Trueif the jpg exists:

import httplib

def exists(site, path):

    conn = httplib.HTTPConnection(site)
    conn.request('HEAD', path)
    response = conn.getresponse()
    conn.close()
    return response.status == 200

print exists('uploads1.wikiart.org',
             '/images/vincent-van-gogh/vincent-s-bedroom-in-arles-1889.jpg')

However, if I send it to a url that doesn't exist, like 'uploads1111.wikiart.org',I get a socket error that says:

socket.error: [Errno 10060] A connection attempt failed 
because the connected party did not properly respond after a period of time

I searched for an answer and found something to do with the errno module but wasn't able to apply that code to my own successfully. I'm trying to catch any socket errors and return False if there is one.

1
  • 1
    Why can't you just catch socket.error? Commented Oct 19, 2014 at 16:15

1 Answer 1

3

Answer to my own question:

import httplib
import socket


def exists(site, path):

    try:
        conn = httplib.HTTPConnection(site)
        conn.request('HEAD', path)
        response = conn.getresponse()
        conn.close()
        return response.status == 200

    except socket.error:
        return False
Sign up to request clarification or add additional context in comments.

Comments

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.