python接口测试(叮趣接口实例)
#————————————————————————————————————叮趣接口实例——————————————————————————————————————————————————————————————————
import requests #先导入包,这是必须的 import json import re class AddBook(object): def __init__(self, name,phone='78787'):#默认值78787 self.name = name self.phone=phone def get_denglu(self): u'''实现叮趣登录接口(GET请求)''' url = "https://services.ding-qu.com/v3/user/login/accountpassword?logul_longitude%5B%5D=113.357769&logul_longitude%5B%5D=23.134109&logul_precision=65.000000&mu_device=683028364449151212084245&mu_password=8a05529ec2d68a4d81b3ca6937ca2728&uservalues=18612260669"#测试的接口url headers = {"Content-Type":"application/json"} r = requests.get(url = url,headers = headers) print (r.text) #获取响应报文 #print (r.status_code)#响应状态码 wei=r.text rr=re.findall(r"access_token\":\"(.+?)\"",wei) a= "" .join(rr) self.phone=a #print(self.phone)#打印全局变量 if r.status_code==200: print('登录成功') else: print ('登录失败') def get_phone(self): u'''获取叮趣首页接口(POST请求)''' while self.name<10: #print(self.name) url = 'https://services.ding-qu.com/v3/user/tansuo/getlist' data={"mu_id":889,"mdq_picturecoordinate":[113.357725,23.134038],"page":{"current":1,"rowcount":50,"srotfield":[]}} headers ={'Content-Type':'application/json','access_token':''+(self.phone)}#引用变量self.phone(拼接字符串) r = requests.post(url,json = data,headers = headers) chen=r.json()#把响应的json数据写入到chen # print(chen)#打印响应json数据 # print(r.url)#返回url地址 # print (r.status_code)#响应状态码 print(r.text)#打印响应数据 a=r.text chen='操作成功' in a if chen==True: print("获取首页列表-断言成功") else: print("获取首页列表-断言失败") return r.url # 调用 if __name__ == "__main__": Detian = AddBook(5)#创建对象,只传一个值 Meng = AddBook(5, '18210413002')#实例化类,或为类创建对象 chen1=Meng.get_denglu()#调用登录接口 #print(chen1) Meng.get_phone() #print (Detian.get_phone())#通过Detian对象调用(调用首页接口) #print (Meng.get_phone())#通过Meng对象调用
1.基本请求示例:
import requests ##_________________________________________post请求____________________________________________________ def post_url(dada): headers = {'content-type': 'application/json', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} r = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers) print(r.text) if __name__ == '__main__': data = {'some': 'data'}#参数 post_url(data) #_________________________________________get请求_____________________________________________________ #1、无参数实例 ret = requests.get('https://qqlykm.cn/api/api/tq.php?city=%E5%8C%97%E4%BA%AC') print('请求的url:',ret.url) print('响应内容_自动解码:\n',ret.text)#自动解码 print('响应内容_不解码:\n',ret.content.decode('UTF-8'))#默认不解码(bytes格式), 需要decode解码 print('请求方法:',ret.request) print('状态码',ret.status_code) print ('响应头部字符编码:',ret.encoding) print('服务器发回的cookies:',ret.cookies) print('响应头:\n',ret.headers)##可在响应头查看字段print(ret.headers['Content-Type']) print('从发送请求到响应的时间/秒:',ret.elapsed) print ('响应转字典:\n',ret.json())#python中json就是字典 print('响应的解析头链接',ret.links) ## 2、有参数实例 payload = {'key1': 'value1', 'key2': 'value2'} ret = requests.get("http://httpbin.org/get", params=payload) print(ret.url) print(ret.text) # #3.带有headers headers={"Content-Tpye":"application/x-www-form-urlencoded"} url='http://httpbin.org/get' ret = requests.get(url=url, headers = headers) print('请求的url',ret.url) print('响应内容',ret.text) ## 4.带有headers及参数 headers = {"User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;"}##设置请求Headers头部 #请求输入参数 p = {"city":"广州"} url_temp = "https://qqlykm.cn/api/api/tq.php?" #requests发送请求 result = requests.get(url_temp,headers=headers,params=p) print(result.status_code) print(result.text)
案例二:
#!/usr/bin/env python # encoding: utf-8 import requests from requests.exceptions import ReadTimeout,ConnectionError,RequestException def chen(): try: headers = {"User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;"}##设置请求Headers头部 p = {"city":"广州"} url_temp = "https://qqlykm.cn/api/api/tq.php?" result = requests.get(url_temp,headers=headers,params=p,allow_redirects=True,verify=False,timeout=0.5)#allow_redirects是否重定向,,verify是否证书验证(默认True,False跳过验证),,timeout超时时间-单位秒 print(result.status_code) print(result.text) except ReadTimeout: print('读取超时') if __name__ == '__main__': chen()
2.设置超时时间&异常捕获:
#!/usr/bin/env python3 #coding: utf-8 import time import requests url = 'http://chenwei.com' print(time.strftime('%Y-%m-%d %H:%M:%S')) try: html = requests.get(url, timeout=5) print('打印响应内容',html.read()) print('返回url',html.url) print('success') #捕获超时类型 except requests.exceptions.RequestException as e: print('已经超时了') print(e) print(time.strftime('%Y-%m-%d %H:%M:%S'))
3.代理请求:
#!/usr/bin/env python # encoding: utf-8 import requests url = 'http://test.yeves.cn/test_header.php' params = {'id':'1','name':'test'} #params = {'key1': 'value1', 'key2': ['value2', 'value3']} headers = { 'User-Agent':'test' } cookies = {'name':'gggg'} proxies = { "http": "http://36.36.115.170:8197", } #param请求参数,allow_redirects是否启动重定向,proxies代理ip,headers请求头 response = requests.get(url,params=params,cookies=cookies,allow_redirects=False,proxies=proxies,headers=headers) print(response) print(response.status_code) print(response.encoding) print(response.headers) print(response.url) print(response.json()) print(response.history)
4.多字段对比场景(可在ms中使用)
# _______________________判断a==a1,b==b1,c==c1,d==d1_______________________________ a = ["chenwei", "wei"] b = "b" c = "c" d = { "name": "点击量", "historyBack": False, "assetTypes": [ { "operation": "DISABLE", "feed_delivery_search": "DISABLED" } ], "flag": "" } a1 = ["chenwei", "wei"] b1 = "b" c1 = "c" d1 = { "name": "点击量", "historyBack": False, "assetTypes": [ { "operation": "DISABLE", "feed_delivery_search": "DISABLED" } ], "flag": "chenwei" } # 把变量分别放到list strings = [a, b, c, d] strings1 = [a1, b1, c1, d1] #判断变量是值是否相等 are_equal = all(x == y for x, y in zip(strings, strings1)) if are_equal==True: print("判断多个变量相等:", are_equal) else: print("strings和strings1的值不完全相......") if len(strings) == len(strings1): print("strings和strings1元素个数相同") for i in range(len(strings)): print("原始数据:{}___媒体数据:{}".format(strings[i],strings1[i])) else: print("strings和strings1元素个数不相同") print("strings数据:".format(strings)) print("strings1数据:".format(strings1))
5.重试重试:
import requests from retrying import retry # 定义重试装饰器 @retry(wait_fixed=2000, stop_max_attempt_number=3) def make_request(url): response = requests.get(url, timeout=5) response.raise_for_status() return response # 使用重试装饰器调用请求函数 try: response = make_request('https://example.com') print(response.text) except requests.exceptions.RequestException as e: print(f"请求失败: {str(e)}")
7.POST常见提交方式:
1.表单数据(Form Data):
使用data
参数传递表单数据,可以是一个字典或一个字符串。requests
库会自动将数据编码为表单格式并发送给服务器。示例代码如下:
import requests data = {'username': 'john', 'password': 'secret'} response = requests.post('https://api.example.com/post', data=data)
2.JSON数据:
使用json
参数传递JSON格式的数据。requests
库会自动将数据编码为JSON格式并发送给服务器。示例代码如下:
import requests data = {'name': 'John Doe', 'email': 'john@example.com'} response = requests.post('https://api.example.com/post', json=data)
3.文件上传:
使用files
参数上传文件。files
参数是一个字典,其中键是字段名,值可以是文件对象或文件路径。示例代码如下:
import requests files = {'file': open('file.txt', 'rb')} response = requests.post('https://api.example.com/upload', files=files)
4.自定义请求体:
如果需要更灵活地控制请求体的内容,可以通过data
参数直接传递字符串形式的请求体。示例代码如下:
import requests payload = 'Custom request body' response = requests.post('https://api.example.com/post', data=payload)
相关连接:
https://www.cnblogs.com/lanyinhao/p/9634742.html ............................python3_requests模块详解
https://www.cnblogs.com/ranxf/p/7808537.html ....................................python3_requests模块详解2
https://www.cnblogs.com/paulwinflo/p/11956492.html .......................... requests请求方式
https://blog.csdn.net/weixin_41998715/article/details/105188617 .............. requests的案例
https://www.cnblogs.com/lweiser/p/11033005.html ...............................python爬虫教程(https://blog.csdn.net/qq_42363032/article/details/105615607)
https://www.cnblogs.com/AndyChen2015/p/7418053.html ....................urllib基本使用 urlopen(),Request
https://www.pianshen.com/article/60271230317/ ...............................请求方法参数解释 ,请求参数说
https://blog.csdn.net/m0_50628560/article/details/109674768...............post数据提交常见的三种方式
https://blog.csdn.net/weixin_39616045/article/details/111077448 .........content和text调用的区别
https://blog.csdn.net/weixin_39198406/article/details/81482082 ...........................requests异常类型(代理ip)
https://www.cnblogs.com/wlyd/p/5643421.html..........................................python将接口返回的unicode转为中文显示(https://blog.csdn.net/weixin_42342968/article/details/109621291)
https://blog.csdn.net/smj811504083/article/details/51889751 ..................python 打印json格式的数据中文显示问题(用于接口响应数据解析中文)