问题描述
我正在使用 Requests 库并访问网站以使用以下代码从中收集数据:
r = requests.get(url)
我想为输入不正确的 URL 并返回 404 错误添加错误测试.如果我故意输入一个无效的 URL,当我这样做时:
print r
我明白了:
我想知道如何进行测试.对象类型仍然相同.当我执行 r.content
或 r.text
时,我只是获取自定义 404 页面的 HTML.
如果 r.status_code == 404:# 发出了 404.
演示:
>>>进口请求>>>r = requests.get('http://httpbin.org/status/404')>>>r.status_code404如果您希望 requests
为错误代码(4xx 或 5xx)引发异常,请调用 r.raise_for_status()
:
您还可以在布尔上下文中测试响应对象;如果状态代码不是错误代码(4xx 或 5xx),则认为是真":
如果 r:# 成功响应
如果您想更明确,请使用 if r.ok:
.
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.
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:
.
这篇关于请求——如何判断你是否收到 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!