For various reasons I need to put a Requests call inside a try/except/retry loop, rather mounting a retry condition to a requests session. Expected behaviour is that if a request has been successful, the loop breaks and the code stops. Actual behaviour though is that it repeats the loop from start to finish, with the break statement seemingly having no effect:
import traceback import requests import time for i in range(0, 15): while True: try: headers ={ 'authority': 'www.wikipedia.org', 'method': 'GET', 'path': '/wikipedia.org', 'scheme': 'https', 'accept': '*/*', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', 'referer': 'https://google.com', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36' } r = requests.get(url='https://wikipedia.org', headers=headers) print(i, r.status_code) except Exception as exc: time.sleep(60) print(traceback.format_exc()) print('continue') continue print('break') break print('Finished') What do I need to change to get the desired behaviour?
whileorfor?"break"being printed? What about"finished"? Either you don't expect the for loop to initiate another loop of thewhileloop, or there is an error being caught every time you make a request.