pin_drop当前位置:知识文库 ❯ 图文
requests Response对象详解 - 状态码解析与数据提取技巧
一、概述
Response对象是Python requests库发起HTTP请求后返回的结果对象,封装了服务器响应的所有信息,包括status_code(状态码)、headers(响应头)、text(文本内容)、content(二进制内容)、json()(JSON解析)、cookies(Cookie)等。掌握Response对象的属性和方法,是从HTTP响应中提取所需数据的关键。
二、Response属性与方法
三、获取响应内容的多种方式
Response对象提供了多种获取响应内容的方式,适用于不同场景:
-
response.text:返回解码后的文本字符串,适合HTML页面、JSON文本等文本类响应。自动根据响应头中的编码或response.encoding属性进行解码。
-
response.content:返回原始字节数据(bytes),适合图片、音频、视频等二进制文件下载。不经过任何编码转换,是最可靠的获取方式。
-
response.json():自动将响应体解析为Python字典或列表,适合JSON API响应。内部调用json.loads()处理response.text。
四、代码示例
示例1:Response基本属性
代码示例
import requests
response = requests.get('https://httpbin.org/get')
print(f"状态码: {response.status_code}")
print(f"状态描述: {response.reason}")
print(f"是否成功: {response.ok}")
print(f"编码: {response.encoding}")
print(f"最终URL: {response.url}")
print(f"请求耗时: {response.elapsed}")
print(f"响应头Content-Type: {response.headers.get('Content-Type')}")输出:
代码示例
状态码: 200
状态描述: OK
是否成功: True
编码: utf-8
最终URL: https://httpbin.org/get
请求耗时: 0:00:00.352000
响应头Content-Type: application/json示例2:响应内容的多种获取方式
代码示例
import requests
response = requests.get('https://httpbin.org/json')
# 方式1:text属性 - 获取文本内容
print(f"text类型: {type(response.text)}")
print(f"text前80字符: {response.text[:80]}")
# 方式2:content属性 - 获取二进制内容
print(f"\ncontent类型: {type(response.content)}")
print(f"content长度: {len(response.content)} 字节")
# 方式3:json()方法 - 解析JSON
data = response.json()
print(f"\njson()类型: {type(data)}")
print(f"JSON键: {list(data.keys())}")输出:
代码示例
text类型: <class 'str'>
text前80字符: {
"slideshow": {
"author": "Yours Truly",
"date": "date of publication",
content类型: <class 'bytes'>
content长度: 429 字节
json()类型: <class 'dict'>
JSON键: ['slideshow']示例3:状态码处理与异常
代码示例
import requests
# 正常请求
response1 = requests.get('https://httpbin.org/status/200')
print(f"200状态码: {response1.status_code}, ok={response1.ok}")
# 404请求
response2 = requests.get('https://httpbin.org/status/404')
print(f"404状态码: {response2.status_code}, ok={response2.ok}")
# 使用raise_for_status()自动抛出异常
try:
response3 = requests.get('https://httpbin.org/status/500')
response3.raise_for_status()
except requests.exceptions.HTTPError as e:
print(f"HTTPError捕获: {e}")
# 重定向信息追踪
response4 = requests.get('https://httpbin.org/redirect/2')
print(f"\n重定向次数: {len(response4.history)}")
print(f"中间URL: {[r.url for r in response4.history]}")
print(f"最终URL: {response4.url}")输出:
代码示例
200状态码: 200, ok=True
404状态码: 404, ok=False
HTTPError捕获: 500 Server Error for url: https://httpbin.org/status/500
重定向次数: 2
中间URL: ['https://httpbin.org/redirect/2', 'https://httpbin.org/redirect/1']
最终URL: https://httpbin.org/get五、实际应用场景
-
场景1:API数据解析:调用REST API后,通过response.json()解析JSON数据,提取业务字段。这是前后端分离架构中最常见的数据处理方式。
-
场景2:文件下载:通过response.content获取图片、PDF、Excel等二进制数据,然后写入本地文件。适合爬虫抓取资源文件和批量下载场景。
-
场景3:服务健康监控:通过response.status_code和response.elapsed判断服务器健康状态。结合定时任务,可实现简单的服务可用性监控。
六、注意事项
注意1:response.json()在响应内容不是合法JSON时会抛出json.JSONDecodeError异常。建议先用try-except捕获异常,或检查Content-Type是否为application/json。
注意2:text属性使用response.encoding解码,可能存在编码错误(如乱码);content属性返回原始字节,更可靠。遇到中文乱码时,可手动设置response.encoding = 'utf-8'或'gbk'。
注意3:response.url可能与请求URL不同,因为可能发生了重定向。如果需要获取重定向前的URL,可通过response.history属性查看重定向链路。
七、响应内容获取方式对比
根据不同的响应类型和使用场景,选择合适的响应内容获取方式:
小贴士
下载大文件时,不要直接使用response.content,因为它会将整个文件加载到内存中。推荐使用iter_content(chunk_size=8192)分块下载,配合stream=True参数使用:response = requests.get(url, stream=True),这样可以有效降低内存占用。
八、小结
-
Response对象封装了HTTP响应的所有信息,是获取服务器数据的核心接口。
-
text适合获取文本内容,content适合获取二进制内容,json()适合解析JSON响应。
-
使用raise_for_status()可以方便地检查请求是否成功,自动对非2xx状态码抛出异常。
-
通过history属性可以追踪重定向链路,了解请求的完整跳转过程。
九、练习题
练习1
发送GET请求到 https://httpbin.org/get,打印Response对象的所有基本属性(状态码、编码、URL、耗时、响应头)。
练习2
分别使用text、content和json()三种方式获取 https://httpbin.org/json 的响应内容,对比三者的类型和内容差异。
练习3
编写程序,请求 https://httpbin.org/status/404,使用raise_for_status()捕获异常并打印完整的错误信息。
常见问题
1. response.text和response.content有什么区别?
response.text返回的是解码后的字符串(str类型),会自动根据encoding属性进行编码转换;response.content返回的是原始字节数据(bytes类型),未经过任何解码。处理文本用text,处理二进制文件(如图片)用content。
2. response.json()抛出异常怎么办?
response.json()在响应内容不是合法JSON时会抛出json.JSONDecodeError。解决方法:1)先用print(response.text)查看原始内容;2)用try-except捕获异常;3)检查服务器返回的Content-Type是否正确;4)确认请求URL是否返回了预期的JSON数据。
3. 中文乱码如何解决?
如果response.text出现中文乱码,可以手动设置编码:response.encoding = 'utf-8'或response.encoding = 'gbk'。也可以使用response.content.decode('utf-8')手动解码。有些网站响应头中的编码声明与实际编码不一致,需要手动指定正确编码。
4. 如何查看完整的请求和响应信息用于调试?
可以通过以下属性查看:response.request.headers(实际发送的请求头)、response.request.body(请求体)、response.headers(响应头)、response.text(响应体)、response.status_code(状态码)。结合print或logging模块可以完整记录请求响应信息。
5. ok属性和status_code有什么区别?
status_code返回具体的HTTP状态码数字(如200、404、500),ok是布尔值,当status_code < 400时ok为True。ok是一个便捷的快捷方式,适合简单的成功/失败判断;而status_code适合需要区分不同错误状态码的场景。
本文涉及AI创作
内容由AI创作,请仔细甄别