有没有办法区分服务器关闭和 urllib 不存在的 URL?

Is there a way to differentiate between a server being down and a URL not existing with urllib?

我正在编写一个 python 程序来显示网站是否正常运行以及 运行 是否正常运行。到目前为止,这是我的代码:

import urllib.request

weburl = str(input('Enter the URL: '))
#print(urllib.request.urlopen("https://"+ weburl).getcode())


try:
    webcode = urllib.request.urlopen("https://"+ weburl).getcode()
    if webcode == 200:
        print('Website is working')
except:
    print("Website is down or doesn't exist")

但是,如果网站已关闭或不存在,代码 return 在这两种情况下都是 URL 错误。这是服务器停机的错误

Exception has occurred: URLError
<urlopen error [WinError 10061] No connection could be made because the target machine actively refused it>
  File "C:\Programming\Python\test.py", line 4, in <module>
    print(urllib.request.urlopen("https://"+ weburl).getcode())

这里是 URL 不存在的例外情况:

Exception has occurred: URLError
<urlopen error [Errno 11001] getaddrinfo failed>
  File "C:\Programming\Python\test.py", line 4, in <module>
    print(urllib.request.urlopen("https://"+ weburl).getcode())

如何区分服务器停机和 URL 一开始就不存在?我考虑过在 'except:' 行中使用请求和 return 之间的时间,因为当网站根本不存在时它要快得多,但是,我不确定这是否可行由于人们的网速不同。

调用urlopen方法时不应该捕获所有可能的异常,你应该捕获urllib.error.HTTPError一个,它可以告诉你响应的状态码,如下:

import urllib.request
from urllib.error import HTTPError, URLError

weburl = input('Enter the URL: ')

try:
    urllib.request.urlopen(weburl)
except HTTPError as error:
    if error.code == 404:
        print("The server exists but the endpoint does not!")
    else:
        print("The server exists but there was an Internal Error!")
except URLError as error:
    print("The server does not exist!")

当然,除了 HTTPError 之外,还可以抛出其他异常,例如 ValueErrorURLError 等,所以如果您想处理它们,您也可以捕获它们。

编辑:我没有解释好,抱歉。当服务器不存在时也会引发 URLError,因此您也应该捕获它。我以为你只想检查现有服务器的具体端点是否存在,但如果你还想检查服务器是否存在,你还应该捕获 URLError 异常。