Is there a way to prevent a Python fucntion return 'None'

Viewed 31

See this script.... here I am creating a function to return the status code of a URL if it is broken. But the problem is that for some URLs, I am getting "None" returned. How do I prevent this? I don't know what's causing this.

import requests

domain = 'https://www.complianceprime.com/blog/2021/09/26/a-brief-history-of-fair-housing-act/'

headers = {
    'authority': domain,
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'accept-language': 'en-US,en;q=0.9',
    'cache-control': 'max-age=0',
    'dnt': '1',
    'sec-ch-ua': '"Microsoft Edge";v="105", " Not;A Brand";v="99", "Chromium";v="105"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'none',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.33',
}


def getStatus(url):
    global headers
    timeout=5
    try:
        r = requests.head(url,headers=headers,timeout=timeout)
        print(r.status_code)
    except (requests.exceptions.SSLError, requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.MissingSchema, requests.exceptions.Timeout, requests.exceptions.InvalidSchema) as errh:
        print("     Error in URL, ", url)
        return errh.__class__.__name__
    if r.status_code in [301, 302, 400, 403, 404, 500, 501, 502]:
           return str(r.status_code)

print(str(getStatus(domain)))

produces this output:

PS C:\Users\xavi\Desktop> python test.py
200
None

Ideally, I want this function to return the status code of the URL that might be broken otherwise nothing.

0 Answers
Related