我正在使用此代码来检查代理服务器:
def check_proxy(p):
try:
r = requests.get('https://httpbin.org/get', proxies={'https': 'https://%s' % p}, timeout=5)
if r.status_code == 200:
return True
else:
return False
except:
return False
它与工作代理一起工作得很好。几分钟后,由于代理错误而失败:
Traceback (most recent call last):
File "/home/me/Desktop/general/test_proxyt.py", line 22, in check_proxy
r = requests.get('https://httpbin.org/get', proxies={'https': 'https://%s' % p}, timeout=5)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 59, in get
return request('get', url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 48, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 451, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 557, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 413, in send
raise ConnectionError(e, request=request)
ConnectionError: HTTPSConnectionPool(host='httpbin.org', port=443): Max retries exceeded with url: /get (Caused by ProxyError('Cannot connect to proxy.', error(110, 'Connection timed out')))
是否可以设置代理连接超时异常?
也许你可以尝试模块附带的
exceptions
。
def check_proxy(p):
try:
r = requests.get('https://httpbin.org/get', proxies={'https': 'https://%s' % p}, timeout=5)
if r.status_code == 200:
return True
else:
return False
except requests.exceptions.Timeout as e:
# Maybe set up for a retry
print e
except requests.exceptions.RequestException as e:
print e
在此结束循环,这是请求中的一个错误,此后已通过更新到 urllib3 来修复