/ 前言 /
Python中Http请求的库有很多, 例如urllib、urllib2、httplib、httplib2、requests等等, 今天我们来介绍一下requests这个第三方python库, 其自带Restful API和返回数据会自动处理成json格式使得requests
库有着广泛的用途
/ 1 / requests介绍
1 . 1 API
requests
库API
def get(url, params=None, **kwargs):
#TODO
def options(url, **kwargs):
#TODO
def post(url, data=None, json=None, **kwargs):
#TODO
def put(url, data=None, **kwargs):
#TODO
def patch(url, data=None, **kwargs):
#TODO
def delete(url, **kwargs):
#TODO
熟悉Restful风格API的朋友肯定已经看出来了, requests
库自带Restful API,不需要我们再进行封装了
1 . 2 安装方式
pip install requests
pip3 install requests
如果操作系统本身就已经安装了Python2.x,后续又安装了Python3.x,请根据要使用版本选择pip
| pip3
1 . 3 使用方式
这里我们用put():
方法来举例, 其余API都与put():
使用方式是一样的
# 设置http header
headers = {"Content-Type": "application/json"}
response = requests.put(url, data, headers=headers)
# 获取接口返回数据
text = response.text
# 将数据转换为字典
rsp = json.loads(text)
如果是有多个header的话就使用,
分隔
headers = {"Content-Type": "application/json","Authorization": "xxxx"}