我正在使用while循环,我试图运行5分钟并检查它是否得到http响应代码200.问题是如果它没有得到200它将继续运行,但它当网站启动并运行时,不会转到其他地方。
r = requests.head("http://www.testing.co.uk")
while r.status_code != 200:
print "Response not == to 200."
time.sleep(30)
else:
print "Response is 200 - OK"
答案 0 :(得分:3)
重复请求。
r = requests.head("http://www.testing.co.uk")
while r.status_code != 200:
print "Response not == to 200."
time.sleep(30)
r = requests.head("http://www.testing.co.uk")
else:
print "Response is 200 - OK"
答案 1 :(得分:0)
请求应该循环:
numOfRequests = 1000
for i in range(numOfRequests):
r = requests.head("http://www.testing.co.uk")
if r.status_code == 200:
print "Response is 200 - OK"
break
print "Response not == to 200."
time.sleep(30)
答案 2 :(得分:0)
尝试此操作,其中包括最多约5分钟的超时检查:
import time
from datetime import datetime, timedelta
import requests
FIVE_MINUTES = timedelta(minutes=1) * 5
RETRY_DELAY = 30
end_time = datetime.now() + FIVE_MINUTES
while datetime.now() < end_time:
r = requests.head("http://www.testing.co.uk")
if r.status_code == 200:
print "Response is 200 - OK"
break
else:
print "Response not == to 200."
time.sleep(RETRY_DELAY)
else:
print 'Timed out'
N.B大约是因为每个请求将花费不可预测的时间段,例如请求可能会挂起2分钟,而其他请求可能会立即失败。此外,您应该添加异常处理,因为requests
引发了诸如“连接被拒绝”等故障的异常。