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" 
Jesse kraal
  • 323
  • 4
  • 11

1 Answers1

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

Asif Raza
  • 3,435
  • 2
  • 27
  • 43
  • 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. – Jesse kraal Jun 15 '17 at 12:13
  • Add this line `from socket import error as SocketError` above `errno`. – Asif Raza Jun 15 '17 at 12:54
  • I replaced except SocketError, e: in except socket.error as e: I will try this out if it works. Thanks for your help – Jesse kraal Jun 15 '17 at 13:07
  • 1
    Oh I forgot your line of code! Ok I will try it again. – Jesse kraal Jun 15 '17 at 13:17
  • If still your problem not solved try this [Question](https://stackoverflow.com/questions/40851926/exception-for-connectionreseterror-errno-54-connection-reset-by-peer) – Asif Raza Jun 15 '17 at 13:21
  • Grr I still get the same error, the link you send, that is for Python 3.0 I use python 2.7. – Jesse kraal Jun 15 '17 at 13:26
  • Take a Look [Question](https://stackoverflow.com/questions/6163732/python-urllib2-connection-reset-by-peer) and [Documentation handle exception](http://www.voidspace.org.uk/python/articles/urllib2.shtml) – Asif Raza Jun 15 '17 at 13:45