import requests
response_obj = requests.get(url="XXX")
方式一:print(response_obj.text)
方式二:content 二进制形式返回响应正文(文本、图片、视频、声音等)
print(response_obj.content.decode('utf-8')) #decode解码
举例:下载图片并保存
安装PIL 的语法:pip install pillow
from PIL import Image
from io import BytesIO
response_obj = requests.get(url="https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&fmt=auto&app=138&f=JPEG?w=632&h=500")
# print(response_obj.content)
img_obj = Image.open(BytesIO(response_obj.content))
img_obj.save('test.png')
方式三:json形式,如果响应正文为json数据,可直接返回json对象
举例:微信公众平台获取token的接口
import jsonpath
url_params = {
"grant_type":"client_credential",
"appid":"wxXXX",
"secret":"XXX"
}
response_obj = requests.get(url="https://api.weixin.qq.com/cgi-bin/token",params=url_params)
value = jsonpath.jsonpath(response_obj.json(),'$.access_token')[0]
print(value)
方式四:raw 响应正文以原始数据展示,需要在请求中增加参数stream=True 用的最少
response_obj = requests.get(url="XXX",stream=True)
print(response_obj.raw.read(10))
|