当前位置: 首页 > news >正文

处理响应消息

检查HTTP响应的状态码

直接通过reponse对象的status_code属性获取

import requestsresponse = requests.get('http://mirrors.sohu.com/')
print(response.status_code)

200

检查响应消息头

检查HTTP响应的消息头,直接通过response对象的headers属性获取

如果是想要取出一个元素的值:print(response.headers['Content-Type'])

检查响应消息体

若想获取响应消息体的文本内容,直接通过response对象的text属性来获取

import requestsresponse = requests.get('http://mirrors.sohu.com/')
print(response.text)

字节串 -> 字符串 ;那么requests库是以什么编码格式把HTTP响应消息体中的字节串解码为字符串的呢 ?

—— 通常requests会根据响应消息头(比如Content-Type) 对编码格式进行推测,(Content-Type:text/html ; charset = utf-8 就是指定文本格式为html , 编码格式为utf-8)但有时候,服务端不一定会在消息头中指定编码格式,就会导致推测有误,就需要我们指定编码格式

import requestsresponse = requests.get('http://mirrors.sohu.com/')
response.encoding='utf8'
print(response.text)

如果想要直接获取消息体中字节串的内容,可采用content属性

import requestsresponse = requests.get('http://mirrors.sohu.com/')
print(response.content)

如果想转换成字符串 

 

import requestsresponse = requests.get('http://mirrors.sohu.com/')
print(response.content)


http://www.mrgr.cn/news/19929.html

相关文章:

  • 深拷贝与浅拷贝
  • 基于Java+SpringBoot+Vue的抗疫物资管理系统
  • 【UEFI基础】SMBIOS基础和使用
  • [Mdfs] lc131. 分割回文串(子集型枚举+选不选+选不选细节+回文串预处理优化+dp枚举顺序+好题)
  • Fine3399或rk3399\sw799刷armbian创建热点
  • 地平线Sparse4D论文解析(含论文原文)
  • 安全检查报告模板
  • 你必须知道的C语言问题(8)
  • 赶紧码住!8款AI智能论文生成系统,毕业论文编写不难!
  • 基于RT的服务健康状况探测的时间间隔选择问题
  • Spring1~~~
  • 2024 年 Python 学习路线推荐,附学习书籍,学习视频(建议收藏)
  • turbovnc 服务端、客户端安装
  • 2024.9.4
  • 火狐浏览器设置秘籍:让https协议下的ws不加密时运行无阻(WebSocket connection HTTPS)
  • 【Java】ApiPost请求返回 `406` 状态码(jackson)
  • STM32 SPI
  • 【电感】基础知识
  • 35.搜索插入位置
  • JSON Hero:视图查看更简单!!【送源码】