0

My script in Python 2.7 scrapes a website every minute, but sometimes it gives the error:

urlopen error [Errno 54] Connection reset by peer>

How I can handle the exception? I am trying something like this:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        print "there is a time-out" 
    pass
        print "There is no time-out, continue" 

1 Answer 1

2

You can handle the exception like this:

from socket import error as SocketError
import errno    

try:
    urllib2.urlopen(request).read()
except SocketError, e:
     errorcode = e[0]
     if errorcode!=errno.ECONNREFUSED:
        print "There is a time-out"
        # Not the error we are looking for, re-raise
        raise e

You can read Error Code

Sign up to request clarification or add additional context in comments.

7 Comments

I have import your code into my script and after a half hour I receive the error: except SocketError, e: NameError: name 'SocketError' is not defined.
Add this line from socket import error as SocketError above errno.
I replaced except SocketError, e: in except socket.error as e: I will try this out if it works. Thanks for your help
Oh I forgot your line of code! Ok I will try it again.
If still your problem not solved try this Question
|

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.