Python response.read之后错误消息上的If条件

Python response.read之后错误消息上的If条件,python,urllib2,Python,Urllib2,是否可能在Hi目录被删除(或服务器不可用)时运行上述代码,而不是崩溃时,执行如下操作 response = urllib2.urlopen("http://example.com/Hi") html = response.read() 您可以使用请求模块 只需在收到请求后,检查状态代码 导入请求 r=请求。获取('http://httpbin.org/status/404') 打印(r.status_code)#输出为int:404 如果一切正常 if html==404

是否可能在Hi目录被删除(或服务器不可用)时运行上述代码,而不是崩溃时,执行如下操作

response = urllib2.urlopen("http://example.com/Hi")
html = response.read()

您可以使用
请求
模块
只需在收到请求后,检查状态代码

导入请求
r=请求。获取('http://httpbin.org/status/404')
打印(r.status_code)#输出为int:404
如果一切正常

if html==404:
    print("No response")
如果未找到页面

if r.ok:
    # cool stuff :)
阅读更多内容:

if r.status_code == 404:
    # so sad :(