如何使用请求在python中引发错误

时间:2019-02-18 11:43:22

标签: python exception python-requests python-3.6

我使用python从某些网址中获取内容。因此,我有一个URL列表,除了其中一个可以获取404的URL之外,其他都不错。我想像这样获取

for url in urls:
    r = requests.get(url)

    try:
        r.raise_for_status()
    except RuntimeError:
        print('error: could not get content from url because of {}'.format(r.status_code))

但是现在,是否会提取出raise_for_status()引发的异常?如果出现错误,如何打印自己的错误代码?

2 个答案:

答案 0 :(得分:0)

您需要修改try catch block

try:
     r = requests.get(url)
     r.raise_for_status()
except requests.exceptions.HTTPError as error:
     print error

答案 1 :(得分:0)

您可以创建自己的异常class并提出它,

class MyException(Exception):
    pass
...
...
for url in urls:
    r = requests.get(url)
    try:
        r.raise_for_status()
    except requests.exceptions.HTTPError as error:
        raise MyException('error: could not get content from url because of {}'.format(r.status_code))