3 requests
# 序
# 工具 vs 代码?
工具:
优点:通常有可视化界面来降低使用门槛、有具体的使用步骤说明、对环境的依赖较小
缺点:扩展受限、复用手段有限、缺乏通用性
代码:
优点:扩展性强、复用性强
缺点:有技术门槛、对环境有依赖
工具和代码的选择应该基于项目场景。
# 为什么是requests库?
接口自动化测试需要使用代码发送请求到服务器,这里用来发送请求 和 解析响应 的库就是requests库了
*官方中文文档:https://requests.readthedocs.io/zh_CN/latest/
# 安装requests
方式1: 启动命令行,联网的前提下键入:pip install requests
方式2:
在pipy搜索requests
下载.whl文件
cmd切换目录到本地.whl文件同级目录
pip install xxxx.whl
# requests库快速入门
# 发送请求的方法
#get请求
requests.get(url, params=None, **kwargs)
Sends a GET request.
参数:
url – URL for the new Request object.
params – (optional) Dictionary, list of tuples or bytes to send in the query string for the Request.
**kwargs – Optional arguments that request takes.
返回:
Response object
Return type:
requests.Response
范例:
ip = 'http://192.168.2.26:8080/'#填写本地的pinter地址
url = ip + 'pinter/com/getSku'
params = {'id':1}#表单类型的参数,要求数据格式是字典
r = requests.get(url = url,params = params)#g
#post请求
requests.post(url, data=None, json=None, **kwargs)
Sends a POST request.
参数:
url – URL for the new Request object.
data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
json – (optional) json data to send in the body of the Request.
**kwargs – Optional arguments that request takes.
返回:
Response object
Return type:
requests.Response
范例:
url = ip + 'pinter/com/login'
data = {
'userName':'admin',
'password':1234
}
r = requests.post(url = url,data = data)
print(r.json())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 处理响应的方法
Response: 响应对象
Response.status_code: 响应状态码
Response.text # 响应⽂文本
Response.json() # 响应转化为json对象(字典)-慎用:如果接⼝口出错或返回格式不不是json格式,使⽤用这个⽅方法会报错
Response.content:返回二进制
1
2
3
4
5
2
3
4
5
# 用来保存会话状态的方法
class requests.Session
# ⽤用来保持session会话,如登录状态
使用方式1:基础调用:
import requests
s = requests.Session()
s.get('http://httpbin.org/get')
<Response [200]>
使用方式2:使用上下文管理器:
with requests.Session() as s:
s.get('http://httpbin.org/get')
<Response [200]>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
上次更新: 2023/09/05, 02:16:11