一、requests 的简单实用
import requests
import json
data = {
'UserName': 'UserName',
'Password': 'Password',
'DeviceId': 'DeviceId',
'DeviceType': "iOS",
'AcquireChannel': 'ios'
}
res = requests.post(url='url', data=data)
print(res.text)
resp = json.loads(res.text)
# 转行成json 格式
result = json.dumps(resp, ensure_ascii=False, indent=2)
# print(result)
二、重构发送post请求
import requests
import json
url = 'https://qambl.p88health.com/mbl/User/Login'
data = {
'UserName': '13300000003',
'Password': '123456',
'DeviceId': '63b94833a5b94e189f2ec383280ee115',
'DeviceType': "iOS",
'AcquireChannel': 'ios'
}
def send_post(url, data):
res = requests.post(url=url, data=data)
return res.json()
resp = send_post(url, data)
print(json.dumps(resp, ensure_ascii=False, indent=2))
二、使用类封装接口测试脚本
import requests
import json
class RunMain:
def __init__(self,url,method,data=None):
self.res = self.run_main(url,method,data)
# return res
def send_get(self,url,data):
res = requests.get(url=url, data=data).json()
return json.dumps(res, ensure_ascii=False, indent=2)
def send_post(self,url,data):
res = requests.post(url=url, data=data).json()
return json.dumps(res, ensure_ascii=False, indent=2)
def run_main(self,url,method,data=None):
res = None
if method == 'GET':
res = self.send_get(url, data)
else:
res = self.send_post(url, data)
return res
if __name__ == '__main__':
url = 'https://qambl.p88health.com/mbl/User/Login'
data = {
'UserName': '13300000003',
'Password': '123456',
'DeviceId': '63b94833a5b94e189f2ec383280ee115',
'DeviceType': "iOS",
'AcquireChannel': 'ios'
}
run = RunMain(url,'POST',data)
print(run.res)
三、post get基类的封装
import requests
import json
class RunMethod:
def __init__(self,url,method,data=None,header=None):
print(--------1)
self.res = self.run_main(url,method,data,header)
# return res
def post_main(self,url,data,header=None):
res = None
if header !=None:
res = requests.post(url=url, data=data, headers=header).json()
else:
res = requests.post(url=url, data=data).json()
return json.dumps(res, ensure_ascii=False, indent=2)
def get_main(self,url,data=None,header=None):
res = None
if header != None:
res = requests.get(url=url, data=data, headers=header).json()
else:
res = requests.get(url=url, data=data).json()
return json.dumps(res, ensure_ascii=False, indent=2)
def run_main(self,url,method,data=None,header=None):
print(-------2)
res = None
if method == 'post':
res = self.post_main(url, data, header)
else:
res = self.get_main(url, data, header)
return res
if __name__ == '__main__':
url = 'https://qambl.p88health.com/mbl/User/Login'
data = {
'UserName': '13300000003',
'Password': '123456',
'DeviceId': '63b94833a5b94e189f2ec383280ee115',
'DeviceType': "iOS",
'AcquireChannel': 'ios'
}
run = RunMethod(url,'post',data)
print(run.res)
附上详细学习网址: https://zhuanlan.zhihu.com/p/588580515
https://requests.readthedocs.io/en/latest/