问题描述
response = urllib2.urlopen("http://example.com/Hi")
html = response.read()
是否有可能在 Hi 目录已被删除(或服务器不可用)的情况下运行上述代码时,而不是崩溃,而是执行如下操作?
if html==404:
print("No response")
解决方法
您可以使用 requests
模块
收到请求后,查看状态码
import requests
r = requests.get('http://httpbin.org/status/404')
print(r.status_code) # the output is the int: 404
如果一切正常OK
if r.ok:
# cool stuff :)
如果页面未找到:
if r.status_code == 404:
# so sad :(