一、get
1、url格式:http://接口地址?key1=value1&key2=value2
2、get方法,有幾個常用的參數:
url:接口的地址
headers:定制請求頭(headers),例如:content-type = application/x-www-form-urlencoded
params:用於傳遞測試接口所要用的參數,這里我們用python中的字典形式(key:value)進行參數的傳遞。
timeout:設置接口連接的最大時間(超過該時間會拋出超時錯誤)
3、舉個例子
import requests # 請求數據 url = 'http://api.shein.com/v2/member/login' header = { 'content-type': 'application/x-www-form-urlencoded' } param = { 'user_id': '123456', 'email': '123456@163.com' } timeout = 0.5 requests.get(url, headers=header, params=param, timeout=timeout) # 發get請求
二、post
1、post方法簡單使用:
帶數據的post,帶header的post,帶json的post,帶參數的post,普通文件上傳,定制化文件上傳,多文件上傳
2、方法定義:requests.post(url,data=None,json=None,**kwargs)。舉個栗子:
import requests # 請求數據 url = 'http://api.shein.com/v2/member/login' header = { 'content-type': 'application/x-www-form-urlencoded' } data = { 'user_id': '123456', 'email': '123456@163.com' } timeout = 0.5 req = requests.post(url, headers=header, data=data, timeout=timeout) # 發post請求 print(req.text) print(type(req.json()))
post方法中的參數,我們不在使用params進行傳遞,而是改用data進行傳遞了
3、實戰1:使用data傳遞參數,返回值正常
url = 'https://app-item.daydaycook.com.cn/kill/helpkKill' data = { 'killPriceGroupId': '1268', 'platform': '4', 'sessionId': 'ee1edff9-b756-40e9-91d5-2753cfff0457', 'token': 'F1A2AA2B6BE386091E929FD433C683D9' } req = requests.post(url, data=data) # 發post請求 print(req.text)
4、實戰2:使用data傳遞參數,報400
url = 'https://backend-web-t1.daydaycook.com.cn/backend/credit/sendCredit.jhtml' data = { 'userId': '1611412', 'content': '111', 'description': '222', 'department': '333' } req = requests.post(url, data=data) # 發post請求 print(req.text)
解決辦法:改用json傳遞參數
url = 'https://backend-web-t1.daydaycook.com.cn/backend/credit/sendCredit.jhtml' data = { 'userId': '1611412', 'content': '111', 'description': '222', 'department': '333' } req = requests.post(url, json=data) # 發post請求 print(req.text)
5、文件上傳,使用files傳遞參數
import requests url = 'https://backend-web-t1.daydaycook.com.cn/backend/credit/readEvent.jhtml' cookies = { 'AUTHORITY.SESSIONID': 'BE8D72F515C0209BE574A7EED421F9CBBD6D26D5A5C3C3AA1E556CB6' } files = { 'file': open('/Users/ddcuser/Downloads/credit_issue.xlsx', 'rb') } req = requests.post(url, cookies=cookies, files=files) # 發post請求 print(req.text)
6、接口的返回值:
text:獲取接口返回值的文本格式
json():獲取接口返回值的json()格式
status_code:返回狀態碼(成功為:200)
headers:返回完整的請求頭信息(headers['name']:返回指定的headers內容)
encoding:返回字符編碼格式
url:返回接口的完整url地址
三、注意
關於失敗請求拋出異常,我們可以使用“raise_for_status()”來完成,那么,當我們的請求發生錯誤時,就會拋出異常。如果你的接口,在地址不正確的時候,會有相應的錯誤提示(有時也需要進行測試)這時,千萬不能使用這個方法來拋出錯誤,因為python自己在鏈接接口時就已經把錯誤拋出,那么,后面你將無法測試期望的內容。而且程序會直接在這里宕掉,以錯誤來計。
def get(self): try: response = requests.get(self.url, params=self.params, headers=self.headers, timeout=float(timeout)) # response.raise_for_status() return response except TimeoutError: self.logger.error("Time out!") return None