如果在 response.read 后出现错误消息的条件

问题描述

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 :(

阅读更多:
https://realpython.com/python-requests/

Requests -- how to tell if you're getting a 404

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...