requests库请求之细枝末节

网友投稿 780 2022-11-22

requests库请求之细枝末节

requests库请求之细枝末节

一、r.text

import requestsr = requests.get('githubcom/timeline.json')print(r.text)

{"message":"Hello there, wayfaring stranger. If you're reading this then you probably didn't see our blog post a couple of years back announcing that this API would Go away: Git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"developer.githubcom/v3/activity/events/#list-public-events"}

1、Requests会根据response.encoding来自动解码来自服务器的内容。大多数unicode字符集都能被无缝地解码【unicode响应内容】。

2、请求发出后,Requests会基于HTTP头部对响应的编码作出有根据的推测。

3、当你访问r.text之时,Requests会使用响应中其推测的文本编码。你可以找出response使用了什么编码,并且能够使用response.encoding 属性来改变它。

4、当你的r.text出现乱码时,修改r.encoding属性;或者是使用r.content.decode('gbk')。

r.encoding = 'gbk'print(r.encoding)print(r.content.decode('gbk'))

二、r.json()

Requests中也有一个内置的JSON解码器,助你处理JSON数据

import requestsr = requests.get('githubcom/timeline.json')print(r.json())

r.json将返回的json格式字符串解码成python字典。r.text返回的utf-8的文本【python数据类型为str】。

三、r.content

如果请求返回的是二进制的图片,你可以使用r.content访问请求响应体。

import requestsfrom PIL import Imagefrom StringIO import StringIOr = requests.get('cn.python-requests.org/zh_CN/latest/_static/requests-sidebar.png')# 读取生成的二进制数据【使用StringIO可以将r.content二进制数据当作文件来操作】--》读取的结果为图片i = Image.open(StringIO(r.content))# 展示图片i.show()

去期待陌生,去拥抱惊喜。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:HTTP状态码
下一篇:判断浏览器类型-----------navigator.userAgent.indexOf()
相关文章

 发表评论

暂时没有评论,来抢沙发吧~