接口调用,有headers,data,params,
需要传入HTTP Header时,我们传入一个dict作为headers参数:headers=dict
要发送POST请求,只需要把get()方法变成post(),然后传入data参数作为POST请求的数据:data = dict
requests默认使用application/x-www-form-urlencoded对POST数据编码。如果要传递JSON数据,可以直接传入json参数:json=dict
params = {'key': 'value'}
r = requests.post(url, json=params) # 内部自动序列化为JSON
上传文件需要更复杂的编码格式,但是requests把它简化成files参数:
>>> upload_files = {'file': open('report.xls', 'rb')}//在读取文件时,注意务必使用'rb'即二进制模式读取,这样获取的bytes长度才是文件的长度。
>>> r = requests.post(url, files=upload_files)
session,一个session一次会话对象,(两种方法,cookie,session模拟浏览器网页操作都可以)
操作cookie
import requests
url = 'https://www.douban.com/login'
data = {"mobilePhone": "17374858677", "userName": "xiaoming"}
res = requests.get(url, data)
cookies = res.cookies
# 充值(sessionId在cookies)
rechanrge_data = {"mobilePhone": "17374858677", "userName": "xiaoming"}
res1 = requests.post(rechanrge_url, data=rechanrge_data, cookies=cookies)
print(res1.text)
使用session不用再携带cookies,如下
session = requests.session()
url = 'https://www.douban.com/login'
data = {"mobilePhone": "17374858677", "userName": "xiaoming"}
res = session.get(url, data)
rechanrge_data = {"mobilePhone": "17374858677", "userName": "xiaoming"}
res1 = requests.post(rechanrge_url, data=rechanrge_data, cookies=cookies)
print(res1.text)
但是要注意不能再次初始化cookie,相当于再次打开浏览器,cookie更新了