这是我的代码。
import requests,time
proxies = {'http':'36.33.1.177:21219'}
url='http://218.94.78.61:8080/newPub/service/json/call?serviceName=sysBasicManage&methodName=queryOutputOtherPollutionList¶msJson=%7B%22ticket%22:%22451a9846-058b-4944-86c6-fccafdb7d8d0%22,%22parameter%22:%7B%22monitorSiteType%22:%2202%22,%22enterpriseCode%22:%22320100000151%22,%22monitoringType%22:%222%22%7D%7D'
i = 0
a = requests.adapters.HTTPAdapter(max_retries=10)
s = requests.Session()
s.mount(url, a)
for x in xrange(1,1000):
time.sleep(1)
print x
try:
r= s.get(url,proxies=proxies)
print r
except Exception as ee:
i = i + 1
print ee
print 'i=%s' % i
代理有点不稳定,所以我设置了max_retries,但是有时候它仍然有异常,所以在每次重试之后有一些方法可以执行吗?
答案 0 :(得分:11)
仅使用requests
库,这是不可能的。但是,您可以使用backoff之类的外部库。
backoff
提供了一个装饰器,你将它包装在你的函数周围。示例代码:
@backoff.on_exception(backoff.constant,
requests.exceptions.RequestException,
max_tries=10, interval=10)
def get_url(url):
return requests.get(url)
上述代码会等待10秒,以便在requests.exceptions.RequestException
的每个例外进行下一次重试,并尝试10次,如max_tries
中所述。