【发布时间】:2021-06-24 20:57:12
【问题描述】:
response = urllib2.urlopen("http://example.com/Hi")
html = response.read()
是否有可能在删除 Hi 目录(或服务器不可用)的情况下运行上述代码,而不是崩溃,而是执行如下操作?
if html==404:
print("No response")
【问题讨论】:
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
如果一切都正常
if r.ok:
# cool stuff :)
如果页面未找到:
if r.status_code == 404:
# so sad :(
【讨论】: