欢迎来到资源库(www.zyku.net)

Python教程

当前位置:首页 > 网络编程 > Python教程 > 数据类型

python中response.text 和response.content的区别详解

时间:2022-01-25|栏目:Python教程|点击:|我要投稿

1.response.text

- 类型:str

- 解码类型: 根据HTTP 头部对响应的编码作出有根据的推测,推测的文本编码

- 如何修改编码方式:response.encoding=”gbk”

2. response.content

- 类型:bytes

- 解码类型: 没有指定

- 如何修改编码方式:response.content.deocde(“utf-8”)

3.获取网页源码的通用方式:

response.content.decode()
response.content.decode(“GBK”)

解码方式可以根据响应头中找到Content-Type:text/html;charset=utf-8或者网页源码中content="text/html;charset=utf-8''来决定.

response.text

以上三种方法从前往后尝试,能够100%的解决所有网页解码的问题

所以:更推荐使用**response.content.deocde()**的方式获取响应的html页面

补充:python3中requests 常用response

看代码吧~

import requests
res = requests.get("http://127.0.0.1:9092")

print(res.status_code) # 200
print(res.url) # http://127.0.0.1:9092/
print(res.headers) # {'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '10', 'Date': 'Sat, 22 Dec 2018 13:36:16 GMT', 'Connection': 'keep-alive'}
print(res.cookies) # <RequestsCookieJar[<Cookie cid=hello world for 127.0.0.1/>]>
print(res.text) # 8248154254
print(res.content) # b'8248154254' 写图片
print(res.cookies['cid']) # hello world

# 爬取 图片
r1 = requests.get('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545496551516&di=8ed19596bc72aa87299ed7f234830128&imgtype=0&src=http%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201107%2F31%2F20110731155631_htMcs.jpg')
b = r1.content
with open('hao.jpg','wb') as f:
    f.write(b)

(资源库 www.zyku.net)

原文链接:https://blog.csdn.net/lbj1260200629/article/details/82997524

上一篇:Python基础之logging模块知识总结

栏    目:Python教程

下一篇:教你用Python实现Excel表格处理

本文标题:python中response.text 和response.content的区别详解

本文地址:https://www.zyku.net/python/9266.html

关于我们 | 版权申明 | 寻求合作 |

重要申明:本站所有的文章、图片、评论等内容,均由网友发表或上传并维护或收集自网络,仅供个人学习交流使用,版权归原作者所有。

如有侵犯您的版权,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:95148658 | 邮箱:mb8#qq.com(#换成@)

苏ICP备2020066115号-1

本网站由提供CDN加速/云存储服务