I am trying to monitor a website but my code doesn't update when the response status code updates

87 views Asked by At

This is my code:

import requests
websiteURL = input("Enter The Website's URL: ")
while True:
    response = requests.get(websiteURL)
    if response.status_code == 200: 
     print('Offline!')
    elif response.status_code == 404:
     print('Online!')

If the website returns a response status code of 200 print("Online!")

But if the website returns a response status code of 404 print("Offline!")

But the response status code doesn't update so it just keeps printing "Online!" if the site returns 200 at first so when the site returns 404 it still keeps printing "Online!" and I only want it to print 1 time and every time the site response status code gets updated it prints the updated response status code

Edit: Details(It Needs To Be In A While Loop I Want To Monitor The Website So That Every Time The Response Status Code Changes It Prints Whether It Went Offline Or Online But The Print Statement Isn't Getting Updated So It Keeps Printing Online Even When The Website Goes Offline That's The Main Problem And Then Maybe If Possible Only Print Whether The Website Is Online Or Offline Only Once And When The Response Status Code Gets Updated It Prints Whether It Has Gone Online Or Offline)

1

There are 1 answers

0
Omer On BEST ANSWER

Using two bool values will work as per your requirement check if its working as you want.

import requests
status=True
status_1=True
while True:
    response = requests.get(input("websiteURL"))
    if response.status_code == 200:
        if status:
            status_1=True
            status=False
            print('Online!')
    
    elif response.status_code == 404:
        if status_1:
            status=True
            status_1=False
            print('Offline!')