requests模块Response类

发布时间 2023-04-16 20:18:06作者: 挖洞404

1、介绍

requests.request函数执行的返回对象即requests.Response类的对象。当然,其他请求函数执行返回也是如此。

2、类和初始化

class Response:
    __attrs__ = [
        "_content",
        "status_code",
        "headers",
        "url",
        "history",
        "encoding",
        "reason",
        "cookies",
        "elapsed",
        "request",
    ]
    def __init__(self):
  • Response类不支持外部创建Response对象初始化

3、属性和方法

(1)响应

print(res, type(res))
# <Response [302]> <class 'requests.models.Response'>
  • 请求执行之后会返回一个响应对象

(2)headers

作用:获取响应的头部字段信息

其类似dict类型,可用通过索引取值,或者str函数转换,或者调用dict类型的方法

如果取值没有该字段,会报错

print(res.headers, type(res.headers))
# {'Server': 'nginx/1.15.5', 'Date': 'Sat, 21 Aug 2021 21:10:41 GMT', 'Content-Type': 'text/html', 'Content-Length': '157', 'Connection': 'keep-alive'} <class 'requests.structures.CaseInsensitiveDict'>
print(res.headers['Server'])
print(res.headers.values())

(3)url、raw、ok、is_redirect、reason、status_code

print(res.url, type(res.url))
print(res.raw, type(res.raw))
print(res.ok, type(res.ok))
print(res.is_redirect, type(res.is_redirect))
print(res.reason, type(res.reason))
print(res.status_code, type(res.status_code))
'''
https://www.baidu.com/ <class 'str'>
<urllib3.response.HTTPResponse object at 0x0000018470426AF0> <class 'urllib3.response.HTTPResponse'>
True <class 'bool'>
False <class 'bool'>
OK <class 'str'>
200 <class 'int'>
'''
  • url:str类型
  • raw:暂时未找到应用方式
  • ok:bool类型,判断是否为200
  • is_redirect:bool类型,判断是否为3xx
  • reason:str类型,状态描述
  • status_code:int类型,状态代码

(4)encoding、apparent_encoding、cookies、history、

print(res.encoding, type(res.encoding))
print(res.apparent_encoding, type(res.apparent_encoding))
print(res.cookies, type(res.cookies))
print(res.history, type(res.history))
'''
ISO-8859-1 <class 'str'>
utf-8 <class 'str'>
<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]> <class 'requests.cookies.RequestsCookieJar'>
[] <class 'list'>
'''
  • encoding:编码,str类型
  • apparent_encoding:表现编码,str类型
  • cookies:自定义类型,可以通过其对象方法操作
  • history:历史,list类型

(5)content、text、links

print(res.text.encode(encoding=res.encoding).decode(res.apparent_encoding))
print(res.content, type(res.content))
print(res.links, type(res.links))
'''
xxx
b'xxx' <class 'bytes'>
{} <class 'dict'>
'''
  • text:内容部分,str类型。其一般会进行字符编码传输,res.encoding指定传输编码。而apparent_encoding指定重新编码
    • 但注意res.encoding参数可能会为None,该请求会报错,所以需要先做判断
    • apparent_encoding一般直接指定为utf-8
  • context:内容部分,bytes字节类型
  • links:字典类型

(6)elapsed、next、is_permanent_redirect

print(res.elapsed, type(res.elapsed))
print(res.next, type(res.next))
print(res.is_permanent_redirect, type(res.is_permanent_redirect))
'''
0:00:00.230697 <class 'datetime.timedelta'>
None <class 'NoneType'>
False <class 'bool'>
'''
  • elapsed:请求的响应时间
  • next:一般是重定向使用的路径
  • is_permanent_redirect:是否永久重定向