我正在使用此代码检查代理服务器:
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')))
是否可以设置代理连接超时异常?
答案 0 :(得分:1)
您可以试试模块附带的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
答案 1 :(得分:0)
要关闭此处的圆圈,这是一个bug in requests,此后已修复。