请求-如何判断您是否收到404

问题:请求-如何判断您是否收到404

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

r = requests.get(url)

我想为输入不正确的URL并返回404错误时添加错误测试。如果我有意输入无效的URL,请执行以下操作:

print r

我得到这个:

<Response [404]>

编辑:

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

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:

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.content or r.text, I simply get the HTML of a custom 404 page.


回答 0

看一下r.status_code属性

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

演示:

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

如果要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.

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

if r:
    # successful response

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

Look at the r.status_code attribute:

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 requests to raise an exception for error codes (4xx or 5xx), call 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’:

if r:
    # successful response

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