0

well, when i test my script, it can work for 3 min like 25 min. Sometimes, i've this error.

File "test.py", line 75, in free
srch = br1.open("url")
File "/usr/lib/python2.7/dist-packages/mechanize/_mechanize.py", line 203,     
in open
return self._mech_open(url, data, timeout=timeout)
File "/usr/lib/python2.7/dist-packages/mechanize/_mechanize.py", line 230, 
 in _mech_open
response = UserAgentBase.open(self, request, data)
File "/usr/lib/python2.7/dist-packages/mechanize/_opener.py", line 193, in    
open
response = urlopen(self, req, data)
 File "/usr/lib/python2.7/dist-packages/mechanize/_urllib2_fork.py", line 
344, in _open
'_open', req)
File "/usr/lib/python2.7/dist-packages/mechanize/_urllib2_fork.py", line  
332, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/dist-packages/mechanize/_urllib2_fork.py", line 
1170, in https_open
return self.do_open(conn_factory, req)
 File "/usr/lib/python2.7/dist-packages/mechanize/_urllib2_fork.py", line 
 1118, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 0] Error>

To resolve it, i have just to launch again the script. I think this error may come from network. Is it possible to bypass it ? Or force my script to redo the request ?

2 Answers2

1

Pretty much taken from the docs...

from urllib.request import Request, urlopen
from urllib.error import  URLError

def download_url(url, attempts):
    for attempt in range(attempts):
        try:
            req = Request(url)
            response = urlopen(req)
        except URLError as e:
            if hasattr(e, 'reason'):
                print('Reason: ', e.reason)
            elif hasattr(e, 'code'):
                print('Error code: ', e.code)
        else:
            return response.read()

    return None

print(download_url('http://www.google.com', 3))
mattjvincent
  • 868
  • 2
  • 11
  • 28
-1
while 1:
    try:
        srch = br1.open("url")
        break                      
    except urllib2.URLError:
        pass

Also this question was already answered here: Python urllib2 URLError HTTP status code.

J. Katzer
  • 97
  • 1
  • 7
  • No, it doesn't work. If i do that, my script goes to the next account. Or i wanna retry the requests on the same account. – a.lejeune626 Jan 27 '18 at 13:50