天天看點

在接口測試中的requests使用總結

主要是自己看滴

響應對象res中的值:1)響應中的.encoding : res.encoding 2)響應中的.status_code : res.status_code 3)響應中的.text : res.text(是字元串格式)4)響應中的.json() : res.json()(是字典格式)5)響應中的.headers : res.headers 6)響應中的.cookies : res.cookies 7)響應中的.content : res.content(以位元組碼擷取響應資訊,包括圖檔、視訊等多媒體格式)

1、get(查詢)請求帶參數:paramas 是字典格式或字元串(推薦使用字典)

1) 請求位址:http://xxx.com?id=1

參數params = {“id”: 1}, 則res = requests.get(url, paramas=params )

2)請求位址:http://xxx.com?id=1,2

參數是params = {“id”: “1,2”}, 則res = requests.get(url, paramas=params )(但是需要注意:逗号,會轉化成ASCI值2C)

3)請求位址:http://xxx.com?id=1&app=test

參數是params = {“id”: 1, “app”:“test”}, 則res = requests.get(url, paramas=params )

2、post(新增)請求:

1)參數params是json格式:是json格式的字元串

請求頭是headers={“Content-Type”:“json”}

res = requests.post(url, json=data, headers=headers)

res = requests.post(url, data=json.dumps(data), headers=headers) # 将字典對象轉換成json字元串 json.dumps(data)

2)參數params是data格式:是字典對象

請求頭是headers={“Content-Type”:“application/x-www-form-urlencoded”}

res = requests.post(url, data=data,headers= headers)

3、put請求(修改):

請求位址:http://xxx.com/id=1/ (注意:必須要指定id)

res = requests.put(url, json=data,headers= headers)

4、delete請求(删除):

請求位址:http://xxx.com/id=1/ (注意:1)不需要headers 2)一般情況是沒有響應text,隻有響應的狀态是204)

res = requests.delete(url)

5、res.encoding:1)檢視預設編碼 2)設定響應編碼格式res.encoding=“utf-8”(針對想用文本中的中文)

6、res.headers:通常用來提取伺服器傳回的token/session

from urllib import parse # 引入拼接url函數

url = parse.urljoin(HOST, excUrl)

7、res.cookies:通常用來提取cookies(傳回的是字典對象)

from requests.cookies import RequestsCookieJar # 引入cookies包

cookies = res.cookies.RequestsCookieJar() # 定義一個cookies對象

cookies.update(res.cookies) # 更新擷取到的cookies

8、res.content: 擷取到圖檔資訊(url 中必須有img等格式)

将擷取到圖檔寫入到某個目錄, 采用二進制格式

with open("…/report/test.png", “wb”) as f:

f.write(res.content)