• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 42次浏览 已收录 0个评论
文章目录[隐藏]

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<div>本文来源gaodai^.ma#com搞#代!码网</div> 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)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python中response.text 和response.content的区别详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址