当无法访问网站时,Python抛出错误
我有以下代码来检查是否有特定的网站可用当无法访问网站时,Python抛出错误,python,Python,我有以下代码来检查是否有特定的网站可用 import urllib.request with open("addresses.txt") as file: url_list = file.read() url_list = url_list.splitlines() print("Chcking the repsonse code for the webiste") for url in url_list: response = urllib.requ
import urllib.request
with open("addresses.txt") as file:
url_list = file.read()
url_list = url_list.splitlines()
print("Chcking the repsonse code for the webiste")
for url in url_list:
response = urllib.request.urlopen(url).getcode()
response = (f"{response} available")
if "200 available" in response:
print(f"{url} is up and running")
else:
print(f"{url} is not reachable")
代码一直正常工作,直到可以访问网站,但是如果网站关闭,它不会打印出“google.com不可访问”的消息,而是抛出一个错误。
很抱歉,如果代码不太专业,我是python新手,因此这里的任何帮助都会很有帮助。您可能需要执行以下操作:
try:
response = urllib.request.urlopen(url).getcode()
response = (f"{response} available")
if "200 available" in response:
print(f"{url} is up and running")
else:
print(f"{url} is not reachable")
except Exception as ex:
print(f"Attempting to contact {url} led to error:\n{ex}")
如果要捕获异常,请将调用包装在
try/except
块中。