什么是Python中的Requests模块?
requests模块是Python中广泛使用的库,用于简化HTTP请求的发送和响应处理。无论是调用API、下载文件、处理复杂会话管理,requests都能提供很好的解决方案。
一、基础使用方法
1.GET请求
GET请求用于获取服务器资源,如:获取商品列表。我们就可以通过传递查询参数在URL中,服务器根据你传的参数返回特定的数据。
import requestsurl = 'http://127.0.0.1:8787/products'
params = {'category':'electronics'}response = requests.get(url,params=params)#输出返回的JSON数据
print(response.json())
2.POST请求
接口测试中,POST请求经常用于发送数据。假设我们测试一个登录接口,需要在报文body处传递用户名和密码作为请求参数。
ipmort requests#设置请求的URL和参数
url = 'http://127.0.0.1:8787/login'
headers = {'Content-Type':'application/x-www-form-urlencoded'}
data = {'username':'testname','password','testpass'}#发起POST请求
response = requests.post(url,headers=headers,data=data)#查看响应状态码和内容
print(response.status_code) #200,就表示请求成功
print(response.text) #返回服务器响应的文本内容
3.GET和POST请求的区别
在实际的项目中,选择POST还是GET取决于数据传递的需求:
GET请求:获取服务器的资源,安全且幂等,参数通过URL传递。
POST请求:提交或修改服务器的资源,不安全且不幂等,参数通过报文Body传递。
注意:这里的安全不是指的数据传递时是否容易被窃取,而是能否修改服务器资源。
二、数据传递格式
1.表单提交与JSON数据
POST请求的数据传输方式主要有两种:表单数据和JSON数据
表单提交:
data = {'username':'testuser','password':'testpass'}
response = requests.post(url,data=data)
JSON提交:
json_data = {'username':'testuser','password':'testpass'}
response = requests.post(url,json=json_data)
看起来没什么区别,但是不同的接口通常有特定的数据格式要求,测试时需要根据接口文档确定数据的传输格式。
三、会话管理与持久性连接
在一些需要多次请求的场景下,使用会话对象Session可以管理持久性连接,避免重复登录的操作。尤其是设计用户登录、会话保持的场景,Session的使用至关重要。
#创建会话对象
session = requests.Session()#使用会话对象进行登录
login_url = 'http://127.0.0.1:8787/login'
session.post(login_url,data={'username':'testname','password':'testpass'})#登录后保护受保护的资源
protected_url = 'http://127.0.0.1:8787/protected'
response = session.get(protected_url)print(response.text)
四、处理响应结果
在自动化测试中,我们不仅要关心接口的响应状态码,还需要处理接口返回的数据格式。requests支持多种返回格式.
文本类型:
print(response.text)
JSON类型:
print(response.json())
二进制内容:
print(response.content) #获取二进制内容,如图片或文件
注意:如果遇到编码问题,可以通过response.encoding或手动解码方式来处理
五、应对HTTPS证书验证
在测试HTTPS接口时,可能会遇到证书验证的错误,尤其是在开发环境下。可以通过以下方式禁用证书验证。
response = requests.get(url,verify=False)
六、错误处理与异常捕获
requests提供了强大的异常处理机制,在测试过程中可以捕获网络错误或超时问题
try:response = requests.get(url,timeout=5)response.raise_for_status()
except requests.exceptions.HTTPError as heep_err:print(f'HTTP error occurred:{http_err}')
except requests.exceptions.RequestException as err:print(f'Other error occurred:{err}')
参考文档:Requests: HTTP for Humans™ — Requests 2.32.3 documentation