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 @ 2021-07-02 13:31  习久性成  阅读(86)  评论(0编辑  收藏  举报