gpt4 book ai didi

Python请求代理连接超时

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:27 25 4
gpt4 key购买 nike

我正在使用这段代码来检查代理服务器:

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

关于Python请求代理连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30568978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com