欢迎访问宙启技术站
智能推送

Python中基于requests库的HTTP响应处理

发布时间:2024-01-17 21:35:31

requests库是Python中常用的第三方库之一,用于发送HTTP请求。处理HTTP响应是使用requests库的重要部分之一,可以通过该库处理HTTP响应的各种信息,包括状态码、响应头、响应体等。

在使用requests库发送HTTP请求后,会返回一个Response对象,该对象中封装了HTTP响应的各种信息。下面是对Response对象的常用方法和属性进行详细说明,并给出使用例子。

1. status_code: 获取HTTP响应的状态码。

- 使用方法:response.status_code

- 返回值:整数类型的状态码。

import requests

response = requests.get('http://www.example.com')
print(response.status_code)  # 输出状态码

2. headers: 获取HTTP响应的头部信息。

- 使用方法:response.headers

- 返回值:字典类型的头部信息。

import requests

response = requests.get('http://www.example.com')
print(response.headers)  # 输出头部信息

3. text: 获取HTTP响应的文本内容。

- 使用方法:response.text

- 返回值:字符串类型的文本内容。

import requests

response = requests.get('http://www.example.com')
print(response.text)  # 输出文本内容

4. content: 获取HTTP响应的二进制内容。

- 使用方法:response.content

- 返回值:字节类型的二进制内容。

import requests

response = requests.get('http://www.example.com/logo.png')
with open('logo.png', 'wb') as f:
    f.write(response.content)  # 保存图片

5. json: 将HTTP响应的内容解析为JSON格式。

- 使用方法:response.json()

- 返回值:JSON格式的内容。

import requests

response = requests.get('http://www.example.com/api/data')
data = response.json()  # 解析JSON内容
print(data['name'])  # 输出JSON中的数据

6. cookies: 获取HTTP响应的Cookie信息。

- 使用方法:response.cookies

- 返回值:CookieJar对象,包含了HTTP响应的Cookie信息。

import requests

response = requests.get('http://www.example.com')
print(response.cookies)  # 输出Cookie信息

7. headers.get(header_name): 获取指定名称的HTTP响应头信息。

- 使用方法:response.headers.get(header_name)

- 返回值:指定名称的头信息。

import requests

response = requests.get('http://www.example.com')
print(response.headers.get('Content-Type'))  # 输出Content-Type头信息

上述是对requests库中处理HTTP响应的常用方法和属性进行了介绍,并给出了相应的使用例子。使用requests库可以方便地发送HTTP请求并处理响应,提供了丰富的功能和灵活的接口,非常适用于网络爬虫、API调用等场景。