超详细python接口自动化测试requests实战教学(详全)

2319 篇文章 33 订阅
1785 篇文章 17 订阅

一、前言

Requests是用python语言基于urllib编写的,采用的是Apache2Licensed开源协议的HTTP库,Requests它会比urllib更加方便,可以节约我们大量的工作

本质就是模拟get与post请求 安装 dos命令窗口

pip  install requests

要是下载慢的话 在 pip install 包名 后面加上 -i + 镜像地址,这样 pip 安装时即可成倍的提速了 pip 安装时提速的格式如下:

pip install 包名 -i https://pypi.tuna.tsinghua.edu.cn/simple

国内主要镜像地址如下:

# 清华:
https://pypi.tuna.tsinghua.edu.cn/simple
# 阿里云:
http://mirrors.aliyun.com/pypi/simple/
# 中国科技大学:
https://pypi.mirrors.ustc.edu.cn/simple/
# 华中理工大学:
http://pypi.hustunique.com/
# 山东理工大学:
http://pypi.sdutlinux.org/
# 豆瓣:
http://pypi.douban.com/simple/

二、模拟get请求

# 模拟get请求
# 第一步导入requests模块
# 第二步模拟get请求
import requests
# get()放法就是用来模拟get请求    url就是请求地址
# reponse获取响应对象   对象名称  包含所有的响应信息
reponse= requests.get(url="http://192.168.0.17/phpwind" )

print(reponse.status_code)    #响应状态码获取
print(reponse.reason)       #响应信息获取
print(reponse.headers)      #响应头部信息获取
print(reponse.text)       #响应正文获取

三、模拟带参数的get请求

# 模拟带参数的get请求
import requests
# 方式一:把url参数写在请求地址后面
# reponse=requests.get(url='http://192.168.0.17/phpwind/read.php?tid=2&fid=2')
# print(reponse.text)

# 方式二:把url参数做成字典,然后在get()方法中  使用参数params传入字典
url_params={
    "tid":2,
    "fid":2

}
reponse=requests.get(url='http://192.168.0.17/phpwind/read.php',
                     params=url_params)
print(reponse.text)

四、解析json数据

# pyhton处理json数据
# 在python中  字典类型的数据就是json的键值对形式    列表类型就是json数组形式
# json数据  必须使用双引号""

import  json

# 字符串和json数据的相互转换
str_01='{"name":"张三","age":20}'
# str_01="{'name':'张三','age':20}"   #json数据必须使用双引号  否则会报错
json_obj_01=json.loads(str_01)    #loads  把字符串转换成json数据  前提字符串必须是json数据
print(json_obj_01)
print(type(json_obj_01))

json_obj_02 = {"name":"张三","age":20}
# 会自动把中文转换成unicode编码
str_02 = json.dumps(json_obj_02,ensure_ascii=False)   #使用ensure_ascii会关闭自动转换
print(str_02)
print(type(str_02))

# json数据解析
import jsonpath      #jsonpath通用的json数据解析模块  java  python 都有这个包
json_obj_03={"name":"张三","age":20}
value=jsonpath.jsonpath(json_obj_03,'$.name')[1]
print(value)

五、模拟post请求

# 模拟post请求编辑标签
import requests,j son,jsonpath

url_ aprams={"access_ token":"57135BrbDZbsPz0iM9LP4icmRRMuRubgXA- rBbKXkvE5HT4fqRT}

post_ data = {"tag" : {"id":103,"name" :“北京老帽”}}

#先将json数据转换成字符串
post_ str = json.dumps(post_data,ensure_ ascii=False)

response = requests.post(url ="https:/ /api.weixin.qq.com/cgi-bin/tags/update",Darams= urL_ aprams,
# json=post_ data #json必须传 json数据

#利用data传入字符串数据 用encode('utf-8.)解决乱码格式
data=post_ str .encode('utf-8'))
print (response. text)

六、获取响应正文text/content/json()/raw

# 获取响应信息
# 响应行  响应头  响应正文


import requests
response=requests.get(url="http://www.baidu.com")
print(response.url)   #获取url
print(response.headers)     #.get()  []去获取单独的头
print(response.encoding)   #获取网页编码格式1
# requests根据 响应信息头中的 charset  字段判断网页编码格式  如果没有该字段  则默认为ISO-8859-1  具体表现为乱码
print(response.apparent_encoding)   #获取网页编码格式2
# requests根据 响应正文中的 charset 进行获取网页编码格式
response.encoding=response.apparent_encoding
# 把响应正文的编码类型设置为由响应正文的charset字段获取
# print(response.text)   #以字符串文本的方式获取响应正文


# 以二进制的方式获取响应正文 (普通网页、下载文件、图片、视频等二进制文件   )
print(response.content.decode('utf-8'))

# 响应正文为二进制数据
import requests
from PIL import Image       #pil操作图片
from io import BytesIO      #字节流

response=requests.get(url="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170719%2F2f4b26eebc3c4c63b25b7e98d65a0cb1_th.jpg&refer=http%3A%2F%2Fimg.mp.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655610368&t=75ee6522d3101672a7ae0667b676c6e6")
img_bytes=BytesIO(response.content)    #把获取的二进制图片对象转换成字节流
img_ogj=Image.open(img_bytes)  #创建图像对象  打开字节流图片
img_ogj.save('test.png')  #保存图片

# 响应正文为json数据
import requests,jsonpath
url_params={
  "grant_type":"client_credential",
   "appid":"wxb61e6693c7244793",
    "secret":"c146872139641af2be50a94a01aee9a7"
}

response=requests.get(url="https://api.weixin.qq.com/cgi-bin/token"
                      ,params=url_params)
# 如果已知道返回的数据格式是json格式的正文    可以直接返回json对象
json_body=response.json()
token_value=jsonpath.jsonpath(json_body,"$.access_token")[0]
print(token_value)

# 响应正文返回原始数据  raw    几乎不用
import requests

response=requests.get(url="https://www.baidu.com",stream=True)
print(response.raw.read(10))   #返回原始套接字内容

七、pil 操作图片

import requests
from PIL import Image       #pil操作图片
from io import BytesIO      #字节流

response=requests.get(url="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170719%2F2f4b26eebc3c4c63b25b7e98d65a0cb1_th.jpg&refer=http%3A%2F%2Fimg.mp.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655610368&t=75ee6522d3101672a7ae0667b676c6e6")
img_bytes=BytesIO(response.content)    #把获取的二进制图片对象转换成字节流
img_ogj=Image.open(img_bytes)  #创建图像对象  打开字节流图片
img_ogj.save('test.png')  #保存图片

八、代理设置

# requests  设置代理    必须有代理服务器打开
import requests

proxy_server={
    "http":"http://127.0.0.1:8888",
    "https":"https://127.0.0.1:8888"
}


response=requests.get(url="http://192.168.0.17/phpwind",
                      proxies=proxy_server)

# 带密码的代理   http://用户名:密码@127.0.0.1:8888

九、超时处理

# 超时设置
import requests

reponse = requests.get(url="http://192.168.0.17/phpwind",
                       # timeout=0.001)#timeout  设置的是float  响应时间是响应超时设置
                       timeout=(0.05, 0.04))  # timeout  设置的是tuple
# 0.05是链接服务器超时时间   0.04表示响应超时时间设置
print(reponse.text)

十、重定向

# requests  是默认支持重定向操作
import requests
# allow_redirects   默认设置为true  支持重定向   true打开  false关闭
response=requests.get(url="http://www.360buy.com",allow_redirects=False)
print(response.history)    #查看重定向过程
print(response.content.decode('utf-8'))

requests在模拟https请求时

如果要模拟的系统需要进行证书认证(极少网站)才能访问

那么此时汇报如下错误 SSL error

超详细python接口自动化测试requests实战教学(详全)

超详细python接口自动化测试requests实战教学(详全)

处理方式: 处理方式一:使用verifyFalse 忽略证书认证过程

超详细python接口自动化测试requests实战教学(详全)
​

新版本的urllib3 不支持 要使用方式一 需要降级urllib3

pip install urllib3==1.25.7 

处理方式二:使用cert=证书路径 来解决

超详细python接口自动化测试requests实战教学(详全)

十一、自带的异常处理

# requests自带的异常处理
# Exception  是所有异常类的父类
# RequestException   是requests  包 异常类的父类
import requests

from requests.exceptions import InvalidURL
from requests.exceptions import RequestException
try:
    response = requests.get(url="https: //www.baidu.com")
except InvalidURL as e:      #子--子
    print('无效的url连接')
except RequestException as e:   #子
    print('请求异常,具体原因未知')
except Exception as e:    #父
    print('系统异常,具体原因未知')
# print(response.text)

最后: 可以在公众号:伤心的辣条 ! 自行领取一份216页软件测试工程师面试宝典文档资料【免费的】。以及相对应的视频学习教程免费分享!,其中包括了有基础知识、Linux必备、Shell、互联网程序原理、Mysql数据库、抓包工具专题、接口测试工具、测试进阶-Python编程、Web自动化测试、APP自动化测试、接口自动化测试、测试高级持续集成、测试架构开发测试框架、性能测试、安全测试等。

学习不要孤军奋战,最好是能抱团取暖,相互成就一起成长,群众效应的效果是非常强大的,大家一起学习,一起打卡,会更有学习动力,也更能坚持下去。你可以加入我们的测试技术交流扣扣群:914172719(里面有各种软件测试资源和技术讨论)

喜欢软件测试的小伙伴们,如果我的博客对你有帮助、如果你喜欢我的博客内容,请 “点赞” “评论” “收藏” 一键三连哦!

  • 2
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值