我怎样才能做到这一点?我应该使用请求还是urllib.error错误例外情况?

2024-04-18 00:13:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试处理来自http响应的异常。你知道吗

我的代码的问题是,我被迫使用and IF条件来捕获http错误代码

if page.status_code != requests.codes.ok:
    page.raise_for_status()

我不相信这是正确的方法,我正在尝试以下

import requests

url = 'http://someurl.com/404-page.html'
myHeaders = {'User-agent': 'myUserAgent'}

s = requests.Session()

try:
    page = s.get(url, headers=myHeaders)
    #if page.status_code != requests.codes.ok:
    #     page.raise_for_status()
except requests.ConnectionError:
    print ("DNS problem or refused to connect")
    # Or Do something with it
except requests.HTTPError:
    print ("Some HTTP response error")
    #Or Do something with it
except requests.Timeout:
    print ("Error loading...too long")
    #Or Do something with it, perhaps retry
except requests.TooManyRedirects:
    print ("Too many redirect")
    #Or Do something with it
except requests.RequestException as e:
    print (e.message)
    #Or Do something with it
else:
    print ("nothing happen")
    #Do something if no exception

s.close()

这总是打印“什么都没发生”,我怎么才能捕捉到所有可能的异常相关的网址?你知道吗


Tags: orhttpifstatuswithpagecodeit

热门问题