Python requests介面測試實現程式碼
阿新 • • 發佈:2020-09-09
1、get方法請求介面
url:顯而易見,就是介面的地址url啦
headers:請求頭,例如:content-type = application/x-www-form-urlencoded
params:用於傳遞測試介面所要用的引數,這裡我們用python中的字典形式(key:value)進行引數的傳遞。
舉個例子:
import requests url="http://api.shein.com/login" header={"content-type":"application/x-www-form-urlencoded"} param={"user_id":123456,"email":"[email protected]"} timeout=0.5 response = requests.get(url,headers=header,params=param,timeout=timeout) # response = requests.request("get",url,params=body,timeout=timeout) print (response.text)
2、post方法請求介面
import requests url="http://api.shein.com/login" header={"content-type":"application/x-www-form-urlencoded"} param={"user_id":123456,"email":"[email protected]"} timeout=0.5 response = requests.post(url,data=param,timeout=timeout) # response = requests.request("post",timeout=timeout) print (response.text)
import requests url = "https://apipc.xinqgj.com/user/login" payload = {"phone":"17779828887","pwd":"Ty+coun/mUj1saGV2OCK6p5kN9MNt8Uznj"} headers = {'Content-Type': 'application/json'} response = requests.request("POST",headers=headers,json = payload) print(response.text)
3、requests.Session()請求介面
import requests session = requests.Session() #定義全域性session,通過 session 保持會話 class Cms(): def login(self): url = "http://192.168.1.110:8080/cms/manage/loginJump.do" header = {"Content-Type": "application/x-www-form-urlencoded"} parmas = {"userAccount": "admin","loginPwd": "123456"} #通過全域性 session 請求介面 res = session.post(url=url,data=parmas) print(res.json()) def queryUserList(self): url = "http://192.168.1.110:8080/cms/manage/queryUserList.do" header = {"Content-Type": "application/x-www-form-urlencoded"} parmas = {"startCreateDate":"","endCreateDate":"","searchValue":"","page":"1"} # 通過全域性 session 請求介面 res = session.post(url=url,data=parmas) print(res.json()) if __name__ == '__main__': Cms().login() Cms().queryUserList()
注意:Python requests模組params、data、json的區別
- requests 模組傳送請求有 data、json、params 三種攜帶引數的方法。
- params 在 get 請求中使用,data、json 在 post 請求中使用
- 常見的 form 表單可以直接使用 data 引數進行報文提交,data 的物件則是 python 中的字典型別
- 如果資料是 json 格式的引數,可直接使用 json 引數進行報文提交
4、介面的返回值操作
text:獲取介面返回值的文字格式
json():獲取介面返回值的json()格式
status_code:返回狀態碼(成功為:200)
headers:返回完整的響應頭資訊(headers['name']:返回指定的headers內容)
encoding:返回字元編碼格式
url:返回介面的完整url地址
import requests url = "https://xxxx.com/user/login" payload = {"phone":"1777982xxxx","pwd":"Ty+coun/mUj1saGV2OCK6p5kN9MNt8UznjaGsQ5A/nKPSH1NZW"} headers = {'Content-Type': 'application/json'} response = requests.request("POST",json = payload) print(response.text) print(response.json()) print(response.status_code) print(response.url) print(response.headers) print(response.encoding)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。