This is simplified version of my code, that I use in some projects.
The logic is simple:
- Send
url to server_response - If status == 200 (
url is valid) -> return ok - If status == 404, try to re-check the
url 5 times every 10 secs (cover the case with bad connections) - If after 5 tries the status still 404 -> return
bad
Want to mention, that this code does not cover other statuses (implement it yourself or change if status == 404: to if status != 200:)
import requests from time import sleep def server_response(url): headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'} tries = 5 while True: response = requests.get(url, headers=headers, stream=True) status = response.status_code if status == 404: # u can change it to 'if status != 200:' in order to cover all status codes except 200 print('\n###################################') print('### THERE IS CONNECTION PROBLEM ###') print('Response code: %d \nURI: %s' % (status, url)) print('###################################\n') sleep(10) tries -= 1 elif status == 200: return 'ok' if tries == 0: return 'bad' list_of_urls = ['www.site1.com', 'www.site2.com'] for url in list_of_urls: status = server_response(url) if status == 'ok': # do something else: # do something