首页 > 解决方案 > 当网站无法访问时,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.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 新手,所以在这里任何帮助都会有所帮助。

标签: 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}")

推荐阅读