python接口测试--发送get/post请求

环境准备

主要是学习requests模块。使用pip进行安装

pip install pytest

pip的时候如果出现Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None))…………
pip的时候各种关卡限制了它的网速,导致网速过慢或者安装失败。
解决办法: pip install pytest -i http://pypi.douban.com/simple

发送get请求

  • 导入requests请求
  • 使用get方法直接访问url
  • 查看返回结果
import requests
# 手机号信息查询接口
url = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=手机号'
re = requests.get(url)
print(re.text)

'''
运行结果:
__GetZoneResult_ = {
    mts:'xxxx',
    province:'重庆',
    catName:'中国电信',
    telString:'xxxxx',
	areaVid:'29404',
	ispVid:'xxxxxxx',
	carrier:'重庆电信'
}
'''

ssl问题

当fiddler工具开启需要调试时,发送https请求,会出现以下错误:
在这里插入图片描述
原因是:https相比http来说安全级别高,需要验证SSL证书
解决:发动request请求时,加上verify=False参数
在这里插入图片描述
但是即使加上这个参数还是会有“InsecureRequestWarning”警告(不会影响运行结果,可以不管)在这里插入图片描述
如果有强迫症,可以导入urllib3包,忽略该警告
在这里插入图片描述

get请求带参数

import requests

# 手机号信息查询接口
url = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm'
# 参数
param = {'tel':'手机号'}
re = requests.get(url, params=param, verify=False)
print(re.text)

发送post请求

可以练习的接口,参考聚合数据
比如:标准电码查询接口,这是接口文档信息
在这里插入图片描述

import requests

# 手机号信息查询接口
test_url = 'http://v.juhe.cn/telecode/to_telecodes.php'

body = {'key':'e76b4e49765feaae490e3d6423e9414c','chars':'你好'}
re = requests.post(url=test_url,data=body)
print(re.json())
'''
{'reason': 'success', 'result': {'telecodes': '0132 1170'}, 'error_code': 0}
'''

post请求可以放在url里面也可以放在body里
body中 常见的请求参数类型有四种:

  • application/json,json=
  • application/x-www-form-urlencoded,data=
  • multipart/form-data(这一种是表单格式的),data=
  • content-Type,data=

比如登录接口的接口文档,application/json:
在这里插入图片描述

import requests

host = 'http://xx.xx.xx.xx:9000'
login_url = host +  '/api/v1/login/'
body = {
    "username":"test",
    "password":"123456"
}
header = {'Content-Type':'application/json'}
# Content-Type: application/json。body用json
re = requests.post(url=login_url, json=body, headers=header)
print(re.json())

application/x-www-form-urlencoded
在这里插入图片描述

import requests

url = 'http://xx.xx.xx.xx:9000/api/v4/login'

body = {
    'username': 'test',
    'password': '123456'
}
# Content-Type: application/x-www-form-urlencoded  body用data
re = requests.post(url, data=body)
print(re.json())

fiddler抓包查看请求参数类型
在这里插入图片描述
注意:如果body部分包含中文,那么需要加上encode(‘utf-8’)r = requests.post(url=url, data=body.encode('utf-8'))

json解析

上面的例子中response返回的是json格式,所以通过.json()转为字典格式。
response返回的数据有三种格式:

  • .content #字节输出byte(当返回的数据出现乱码时,可以用.content)
  • .text #str输出
  • .json() #json格式数据,转为字典格式输出
发布了28 篇原创文章 · 获赞 0 · 访问量 371

猜你喜欢

转载自blog.csdn.net/qq_42098424/article/details/105210409