Python 请求——如何判断你是否收到 404

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15258728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:38:19  来源:igfitidea点击:

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

pythonpython-requests

提问by user1427661

I'm using the Requests library and accessing a website to gather data from it with the following code:

我正在使用请求库并访问网站以使用以下代码从中收集数据:

r = requests.get(url)

I want to add error testing for when an improper URL is entered and a 404 error is returned. If I intentionally enter an invalid URL, when I do this:

我想为输入不正确的 URL 并返回 404 错误添加错误测试。如果我故意输入一个无效的 URL,当我这样做时:

print r

I get this:

我明白了:

<Response [404]>

EDIT:

编辑:

I want to know how to test for that. The object type is still the same. When I do r.contentor r.text, I simply get the HTML of a custom 404 page.

我想知道如何测试。对象类型仍然相同。当我执行r.contentor 时r.text,我只是获取自定义 404 页面的 HTML。

采纳答案by Martijn Pieters

Look at the r.status_codeattribute:

r.status_code属性

if r.status_code == 404:
    # A 404 was issued.

Demo:

演示:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requeststo raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

如果要requests针对错误代码(4xx 或 5xx)引发异常,请调用r.raise_for_status()

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true':

您还可以在布尔上下文中测试响应对象;如果状态代码不是错误代码(4xx 或 5xx),则将其视为“真”:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

如果您想更明确,请使用if r.ok:.