【发布时间】:2021-03-28 19:31:18
【问题描述】:
我刚刚完成了一个简短的程序来检查 URL 是否有效以及可访问性。但是,无论如何从 try/except 块不能正常工作 我不知道为什么。即使我输入正确的 URL,它也不会打印出我需要的结果。
我将列出下面的代码,只需检查 try/except 块:
import os
import requests
import string
def url_check(url):
try:
resp = requests.get(url)
if resp.requests.status_code == 200:
print(f">>> {url} is up!")
else:
print(f">>> {url} is down!") # Normal URL but down
except:
print(f">>> {url} is down!") # invalid URL
return
def restart():
print("\nDo you want to start over? y/n", end=' ')
choice = input()
if choice.lower() == 'y':
main()
elif choice.lower() == 'n':
print("Okay. Bye!")
exit()
else:
print("That's not a valid answer")
restart()
def main():
os.system('clear')
print("Welcome to IsItDown.py!")
print("Please write a URL or URLs you wnat to check. (separated by a comma)")
while True:
urls = input().split(',')
for url in urls:
url = url.strip(string.punctuation).strip().lower()
if "." not in url:
print(f"{url} is not a valid URL")
break
else:
if "http" not in url:
url = "http://" + url
url_check(url)
restart()
if __name__ == "__main__":
main()
【问题讨论】:
-
永远不要用黑框和通用
try/except完全隐藏异常。至少打印出错误信息。 -
@KlausD.Do you mean by 'except Exception as e:' ?
-
更重要的部分是额外的
print(e)或类似的。
标签: python url python-requests