requests库请求之细枝末节

一、r.text

import requests
r = 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 requests
r = requests.get('githubcom/timeline.json')
print(r.json())

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

三、r.content

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

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

 

 

posted @   习久性成  阅读(90)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示