【问题标题】:If condition on error message after response.read如果在 response.read 后出现错误消息的条件
【发布时间】:2021-06-24 20:57:12
【问题描述】:
response = urllib2.urlopen("http://example.com/Hi")
html = response.read()

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

if html==404:
    print("No response")

【问题讨论】:

    标签: python urllib2


    【解决方案1】:

    您可以使用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 :(
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-23
      • 2015-07-27
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多