requests库详解
2026/8/29 18:01:17 网站建设 项目流程

一、接口文档

https://api.apiopen.top/swagger/index.html#/

http://httpbin.org/

二、接口测试和接口自动化测试场景

目前主流的接口测试工具:( 中小型公司、项目 )

Postman+Newman+Git+Jenkins

Jmeter+Ant+Git+Jenkins

目前主流的接口自动化测试技术:( 大型的公司、项目)

python+requests+pytest+allure+jenkins

三、requests库简介

requests是用来发送http请求以及接收http响应的python第三方库,主要用于接口自动化测试

#安装:

pip install requests

四、requests库常用的方法

1.requests.get()

获取HTML网页的主要方法,对应HTTP的GET

语法:get(url, params=None, **kwargs) #url是接口地址,params用于传参

2.requests.post()

向HTML网页提交POST请求的,对应HTTP的POST

语法:post(url, data=None, json=None, files=None **kwargs) #url是接口地址,data用于传参,json也用于传参,files用于上传文件

data和json传参选哪个:主要是通过请求头中的Content-Type来区分

Content-Type:作用是服务器要求传入的报文的内容类型

四大要素:请求方式(method),请求路径(url),请求头(headers),请求正文(params、data、json)

2.1.在postman中四种传参方式对应的Content-Type的值如下:

form-data对应的Content-Type : multipart/form-data; boundary=<calculated when request is sent> #文件上传 x-www-from-urlencoded对应的Content-Type : application/x-www-form-urlencoded #表单提交 raw分为以下几种: text对应的Content-Type : text./plain javscript对应的Content-Type : application/javascript json对应的Content-Type : application/json html对应的Content-Type : text/html xml对应的Content-Type : application/xml binary对应的Content-Type : application/binary

Postman官网下载地址 https://www.postman.com/downloads/
MAC版本 https://dl.pstmn.io/download/latest/osx
windows 64版本 https://dl.pstmn.io/download/latest/win64
windows X86版本 https://dl.pstmn.io/download/latest/win32
linux版本 https://dl.pstmn.io/download/latest/linux64

2.2.在requests中data和json传参跟Content-Type的关系如下:

#data 服务器要求Content-Type:application/x-www-form-urlencoded,则需要,data传参:报文是dict类型 服务器要求Content-Type:text./plain,则需要,data传参:报文是str类型 #json 服务器要求Content-Type:application/json,则需要,json传参:报文可以是dict类型 #files 服务器要求Content-Type:multipart/form-data,则需要,files传参

#可以用看接口文档或者用Fidder抓包看Content-Type是什么决定用data还是json

因此:

data:可以传纯键值对的dict(非嵌套的dict),也可以传str格式(如果是嵌套字典那么就需要使用ison.dumps()把嵌套字典转化成ison字符串传参)

json:可以传任何形式的dict( 包括嵌的dict)

#json.loads() 把json字符串转化成dict格式

#json.dumps() 把dict格式转化成ison字符串

3.requests.head()

获取HTML网页头信息的方法,对应HTTP的HEAD

4.requests.put()

向HTML网页提交局部修改请求,对应HTTP的PUT

5.requests.patch()

向HTML网页提交局部修改请求,对应HTTP的PATCH

6.requests.delete()

向HTML网页提交删除请求,对应HTTP的DELETE

7.requests.request()

可以发送所有类型的请求:get,post,put,delete

追朔本源,不管是get,post,put还是delete都是调用的requests.request方法,而requests.reques方法调的是session.request方法

语法:request(method, url, **kwargs) #参数说明: method 请求方式 url 请求路径 params=None get方式传参 data=None post方式传参 json=None post方式传参 headers=None 请求头 cookies=None 请求cookie files=None 文件上传

五、requests模块response返回对象

res.json() 获得返回的字典格式的数据

res.text 获得返回的字符串格式的数据

res.content 获得返回的bytes(字节)类型的数据

res.status_code 返回状态码

res.reason 返回状态信息

res.cookies 返回cookie信息

res.headers 返回响应头

res.request.xxx 返回请求的数据,如:请求头,请求参数等

六、response返回对象状态码

1xx:100-101,信息提示

2xx:200-206,成功类信息

3xx:300-305,重定向类,即跳转,301是永久跳转,302是临时跳转

4xx:400-415,错误类信息,客户端错误(如请求一个不存在的资源就是客户端的错误)

5xx:500-505,错误信息,服务端错误

#常用的状态码:

200:成功,请求的所有数据通过响应报文entity-body部分发送,ok

301:请求的URL指向的资源已经被删除,但在响应报文中通过首部location指明了资源现在所处的新位置,永久重定向,Moved Permanently

302:与301相似,但在响应报文中通过location指明资源现在所处的临时新位置,临时重定向Found

304:客户端发出了条件式请求,但服务器上的资源未曾发生改变,则通过响应此响应状态码通知客户端,Not Modified

401:需要输入账号和密码认证方能访问资源,Unauthorized

403:请求被禁止,Forbidden

404:服务器无法找到客户端请求的资源,Not Found

500:服务器内部错误,Internal Server Error

502:代理服务器从后端服务器收到了一条伪响应,Bad Gateway

七、代码实战

import requests class TestRequest(): access_token="" #全局变量(类变量),通过类名调用 # 获取token def test_post(self): url="https://api.apiopen.top/api/login" headers={ "accept": "application/json", "Content-Type": "application/json" } body={ "account": "1195528321@qq.com", "password": "000000" } res=requests.request(method="post",url=url,headers=headers,json=body) print(res.json()["result"]["token"]) TestRequest.access_token=res.json()["result"]["token"] #将获取的token的值赋给全局变量access_token # 查看用户信息 def test_get(self): url="https://api.apiopen.top/api/getUserInfo" headers={ "accept": "application/json", "token":TestRequest.access_token #这里调用test_post方法写入到全局变量access_token中的token值 } res=requests.request(method="get",url=url,headers=headers) print(res.json()) # 文件上传 def test_file(self): url="http://httpbin.org/post" headers={ "accept": "application/json", "Content-Type": "multipart/form-data" } files = { "file": open("C:\\Users\lasou\Desktop\\11.jpg", "rb") #rb:转换为只读的二进制流 } res=requests.request(method="post",url=url,headers=headers,files=files) print(res.status_code) if __name__=='__main__': p=TestRequest() p.test_post() p.test_get() p.test_file()

执行结果:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjg5NCwiaWQiOjg5NCwiY3JlYXRlZEF0IjoiMjAyMy0wOC0wMyAwMToxMTowOSIsInVwZGF0ZWRBdCI6IjIwMjMtMDgtMDMgMDE6MTE6MDkiLCJkZWxldGVkQXQiOm51bGwsImFjY291bnQiOiIxMTk1NTI4MzIxQHFxLmNvbSIsImxldmVsIjowLCJleHAiOjE2OTc3MTc1OTEsImlzcyI6ImFwaV9vcGVuIiwibmJmIjoxNjk3MTExNzkxfQ.rjtQE090nQnlq1hUE3QUbgEwJd3PZGSPBCzaAZoP85o {'code': 200, 'message': '成功!', 'result': {'updatedAt': '2023-09-25 20:49:44', 'name': 'vorn', 'head_url': '', 'blurb': '', 'birthday': '2014-01-18'}} 200

八、cookie问题

问题描述:

问题分析:

如果请求方式(method),请求路径(url),请求头(headers),请求正文(params、data、json)检查后都没有问题,可以认为这个请求是需要有cookie

还有一种方法可以看是否需要cookie,即从浏览器打开看是否需要cookie:

问题解决-方案一:

提取cookie到全局变量,然后将全局变量中的cookie赋值给其他函数

(1)定义cookie全局变量

(2)提取cookie到全局变量

(3)将cookie传给有需要的接口中

(4)执行结果

问题解决-方案二(较为常用):

使用session建立一个会话,将所有接口都当成一个会话中的几个部分,在同一个会话中这几个接口使用的就会是同一个cookie

演示代码:

import requests class TestRequest(): access_token="" #全局变量(类变量),通过类名调用 sess=requests.session() #定义全局变量sess=requests.session(),将所有的requests都替换为requests.session()就相当于都在一个会话中了 # 获取token def test_post(self): url="https://api.apiopen.top/api/login" headers={ "accept": "application/json", "Content-Type": "application/json" } body={ "account": "1195528321@qq.com", "password": "000000" } res=TestRequest.sess.request(method="post",url=url,headers=headers,json=body) #将所有的requests都替换为requests.session()就相当于都在一个会话中了 print(res.json()["result"]["token"]) TestRequest.access_token=res.json()["result"]["token"] #将获取的token的值赋给全局变量access_token # 查看用户信息 def test_get(self): url="https://api.apiopen.top/api/getUserInfo" headers={ "accept": "application/json", "token":TestRequest.access_token #这里调用test_post方法写入到全局变量access_token中的token值 } res=TestRequest.sess.request(method="get",url=url,headers=headers) #将所有的requests都替换为requests.session()就相当于都在一个会话中了 print(res.json()) # 文件上传 def test_file(self): url="http://httpbin.org/post" headers={ "accept": "application/json", "Content-Type": "multipart/form-data" } files = { "file": open("C:\\Users\lasou\Desktop\\11.jpg", "rb") #rb:转换为只读的二进制流 } res=TestRequest.sess.request(method="post",url=url,headers=headers,files=files) #将所有的requests都替换为requests.session()就相当于都在一个会话中了 print(res.status_code) if __name__=='__main__': p=TestRequest() p.test_post() p.test_get() p.test_file()

执行结果:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjg5NCwiaWQiOjg5NCwiY3JlYXRlZEF0IjoiMjAyMy0wOC0wMyAwMToxMTowOSIsInVwZGF0ZWRBdCI6IjIwMjMtMDgtMDMgMDE6MTE6MDkiLCJkZWxldGVkQXQiOm51bGwsImFjY291bnQiOiIxMTk1NTI4MzIxQHFxLmNvbSIsImxldmVsIjowLCJleHAiOjE2OTc3MTg0OTEsImlzcyI6ImFwaV9vcGVuIiwibmJmIjoxNjk3MTEyNjkxfQ.0Wp93hzulR3x8kvKOk-ifD7yBp411pLN6HgitmGtRJU {'code': 200, 'message': '成功!', 'result': {'updatedAt': '2023-09-25 20:49:44', 'name': 'vorn', 'head_url': '', 'blurb': '', 'birthday': '2014-01-18'}} 200

九、总结

1.发送get请求

2.发送post请求,以及post请求2中传参方式差异,差异主要来自他们的请求头(Content-Type相关)

3.文件上传怎么做

4.cookie的鉴权怎么处理,包括带请求头的接口怎么做(如果接口带请求头就类似请求正文那样添加即可,如下图),包括接口关联怎么处理(例如文章中的token关联,全局变量使用)

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询