[Web自动化] Requests模块响应的内容

6.2 响应的内容

使用requests方法后,会返回一个response对象,其存储了服务器响应的内容。而response对象中的request对象则存储了相关请求内容。

6.2.1 response.request对象:请求内容

py 复制代码
import requests
from icecream import ic
response = requests.get(url='http://dict.baidu.com/s', params={'wd': 'python'})
request = response.request
ic(request.method)# 请求方法
ic(request.url)# 请求地址
ic(request.headers)# 请求头
ic(request.body)# 请求体(正文)
ic(request._Cookies)# 请求Cookies
ic(request.hooks)# 请求钩子

13:22:11|> request.method: 'GET'

13:22:11|> request.url: 'https://dict.baidu.com/s?wd=python'

13:22:11|> request.headers: {'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '/ ', 'Connection': 'keep-alive'}

13:22:11|> request.body: None

13:22:11|> request._Cookies: <RequestsCookieJar\[\]>

13:22:11|> request.hooks: {'response': \[\]}

6.2.2 response对象:响应内容

py 复制代码
import requests
from icecream import ic
response = requests.get(url='http://dict.baidu.com/s', params={'wd': 'python'})
ic(response.apparent_encoding)# 响应编码
ic(response.connection)# 连接类型
(response.content)# 响应内容
ic(response.Cookies)# 响应Cookie
ic(response.encoding)# 编码
ic(response.headers)# 响应头
ic(response.is_permanent_redirect)# 是否永久重定向
ic(response.is_redirect)# 是否重定向
ic(response.links)# 响应链接
ic(response.ok)# 响应状态码是否为200
ic(response.raw)# 原始响应体
ic(response.reason)# 响应状态码原因
ic(response.request)# 发送请求的请求对象
ic(response.status_code)# 响应状态码
(response.text)# 响应内容
ic(response.url)# 响应url
ic(r.history)# 返回重定向信息,当然可以在请求是加上allow_redirects = false 阻止重定向

13:35:42|> response.apparent_encoding: 'utf-8'

13:35:42|> response.connection: <requests.adapters.HTTPAdapter object at 0x000002275A16F0A0>

13:35:42|> response.Cookies: <RequestsCookieJarCookie(version=0, name='BAIDUID', value='7AC84A542BEF4BA0FCAF5193D6ABD531:FG=1', port=None, port_specified=False, domain='.baidu.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1752384942, discard=False, comment=None, comment_url=None, rest={}, rfc2109=True)>

13:35:42|> response.encoding: 'UTF-8'

13:35:42|> response.headers: {'Content-Encoding': 'gzip', 'Content-Type': 'text/html; charset=UTF-8', 'Date': 'Sat, 13 Jul 2024 05:35:42 GMT', 'P3p': 'CP=" OTI DSP COR IVA OUR IND COM "', 'Server': 'Apache', 'Set-Cookie': 'BAIDUID=7AC84A542BEF4BA0FCAF5193D6ABD531:FG=1; expires=Sun, 13-Jul-25 05:35:42 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1', 'Tracecode': '21419605820294162442071313', 'Vary': 'Accept-Encoding', 'Transfer-Encoding': 'chunked'}

13:35:42|> response.is_permanent_redirect: False

13:35:42|> response.is_redirect: False

13:35:42|> response.links: {}

13:35:42|> response.ok: True

13:35:42|> response.raw: <urllib3.response.HTTPResponse object at 0x000002275A436920>

13:35:42|> response.reason: 'OK'

13:35:42|> response.request: <PreparedRequest GET>

13:35:42|> response.status_code: 200

13:35:42|> response.url: 'https://dict.baidu.com/s?wd=python'

13:35:42|> response.history: \>]

响应response的content和text的区别:
1. content
类型:bytes
描述:content属性以字节(bytes)形式返回原始响应体。这意味着,无论响应的Content-Type是什么,content都会直接以字节形式返回数据。这对于需要处理二进制数据(如图片、PDF文件或任何非文本文件)的场景特别有用。
使用场景:当你需要处理非文本响应体,或者需要确保数据的原始性时(例如,防止编码问题影响数据),应使用content。
2. text
类型:str
描述:text属性以字符串(str)形式返回响应体的内容。在返回之前,requests会根据响应的Content-Type头部信息自动尝试对内容进行解码。这意味着,如果响应是JSON、HTML或其他文本格式,text属性将提供一个易于阅读和处理的字符串表示。
使用场景:当你需要处理文本数据(如HTML页面、JSON响应等)时,应使用text。它简化了文本数据的处理过程,因为你不需要自己处理编码问题。
注意事项

默认情况下,requests库会根据HTTP头部中的charset参数来解码text属性。如果没有指定charset,则requests会尝试使用chardet库来猜测编码。

当你需要访问JSON响应时,可以使用response.json()方法,它会解析text(或content,如果text解析失败)为Python字典。这比手动解析JSON字符串要方便得多。

需要注意的是,如果响应体不是有效的文本(例如,是二进制数据),尝试访问text属性可能会引发错误,因为解码过程可能会失败。在这种情况下,你应该使用content属性。

6.2.3 response对象:相关操作

py 复制代码
r.encoding = 'utf-8'# 设置编码
r.encoding = r.apparent_encoding# 自动解码
r.raise_for_status()# 失败请求(非200响应)抛出异常
r.json():将 JSON 格式的响应体内容解析为 Python 字典。
相关推荐
Cosolar1 小时前
LlamaIndex索引类型全解析:原理与实战指南
运维·服务器
小雨下雨的雨3 小时前
井字棋AI机器人实现详解 - Minimax算法实战-鸿蒙PC Electron框架完成
前端·人工智能·算法·华为·electron·鸿蒙
方便面不加香菜4 小时前
Linux--基础IO(一)
linux·运维·服务器
love530love5 小时前
LiveTalking 数字人项目 Windows 部署完全指南(EPGF 架构)
人工智能·windows·python·架构·livetalking·epgf
遇事不決洛必達5 小时前
【Python基础】GIL 锁是什么及其对爬虫的影响
爬虫·python·线程·进程·gil锁
鼎讯信通6 小时前
风电光缆运维提质增效:G-4000A 光缆故障追踪仪破解风场巡检难题
运维·网络·数据库
CryptoPP6 小时前
快速对接东京证券交易所API数据:实战指南与代码示例
开发语言·人工智能·windows·python·信息可视化·区块链
ZC跨境爬虫6 小时前
跟着 MDN 学JavaScript day_7:数学运算与逻辑判断实战测试
开发语言·前端·javascript·学习·ecmascript
三十..6 小时前
MySQL 从入门到高可用架构实战精要
运维·数据库·mysql
fangdengfu1237 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch