I'm coding a short code to check if the url is valid or not. However, when I'm checking for invalid URL it does not respond with any error-ish status code. It just don't run the code.
Can I get some help with this code below:
import requests
import string
# Welcome to IsItDown.py!
# Please write a URL or URLs you want to check. (separated by a comma)
#
# input()
#
# <check for valid URL>
#
# Do you want to start over? (y/n)
# if y:
# elif n: print(Okay. Bye!)
# else: That's not a valid answer
def url_check(urls):
for url in urls:
resp = requests.get(url)
if resp.status_code == 200:
print(f"{url} is up!")
else:
raise Exception(f"{url} is down!")
print("Welcome to IsItDown.py!")
urls = ['google.com .', ' na1v2e12312r.com ']
for index, item in enumerate(urls):
item = item.strip(string.punctuation).strip()
if "http" not in item:
item = "http://" + item
urls[index] = item
print(urls)
try:
url_check(urls)
except Exception as e:
print(e)
Since this is the error you get when you try to access an invalid URL:
NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7efc88f33b50>:
Failed to establish a new connection: [Errno -2] Name or service not known')
That means that in order to catch the error and indicate that the URL is invalid, you'd have to use try
and except
like you're currently doing, except instead you'd catch that specific error:
try:
resp = requests.get(url)
except NewConnectionError:
print(f'Invalid URL: "{url}"')
# at this point, you can continue the loop to the next URL if you want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.