最優雅的http請求庫(python的http請求庫有不少,好比urllib2,urllib3,httplib)。python
requests庫簡介json
requests庫是基於urllib3庫封裝的第三方http請求庫,在python中requests應用最普遍的應該屬網絡爬蟲方面,對於測試來講,咱們對於requests的應用主要是接口測試方面。cookie
實例(1)建立一個請求:網絡
httpbin:這個網站專門是爲了給http作測試用的.app
import requests #導入requests模塊 ''' 號稱最優雅的http請求庫 ''' #建立一個http請求: res_get = requests.get('http://httpbin.org/get‘) #get請求 res_post = requests.post('http://httpbin.org/post', data={'key': 'value'}) #post請求 res_put = requests.put('http://httpbin.org/put', data={'key': 'value'}) #put請求 res_delete = requests.delete('http://httpbin.org/delete') #delete請求 res_head = requests.head('http://httpbin.org/head') #head請求 res_options = requests.options('http://httpbin.org/options') #options請求 #將全部響應結果放入列表中 res_list = [res_get, res_post, res_put, res_delete, res_head, res_options] #打印出全部的響應結果 for i in range(len(res_list)): print(f'\n第{i + 1}個http請求的響應結果:', res_list[i].text)
實例(2)傳遞url參數:函數
import requests
'''
一、帶參數的get請求
get請求使用字典的形式傳參 ''' parm = {'key1': 'value1', 'key2': 'value2'} res_get = requests.get('http://172.25.8.167:1080/get', params=parm) print(res_get.text, '\n請求url爲:', res_get.url) ''' 2、當傳入字典的值爲null時,也會將字典的鍵傳入url中 ''' parm = {'key1': 'value1', 'key2': ''} res_get = requests.get('http://172.25.8.167:1080/get', params=parm) print(res_get.text, '\n請求url爲:', res_get.url) ''' 3、傳入字典的值能夠是一個列表 ''' parm = {'key1': 'value1', 'key2': ['value2', 'value3']} res_get = requests.get('http://172.25.8.167:1080/get', params=parm) print(res_get.text, '\n請求url爲:', res_get.url)
實例(3)post請求傳遞參數:post
import requests import json ''' 一、post請求 以字典的方式傳入參數 ''' parm = {'key': 'value'} res_post = requests.post('http://172.25.8.167:1080/post', data=parm) print(res_post.text) ''' 二、post請求 以元祖列表的方式傳入參數,也能夠直接以元祖方式傳入 ''' parm = [('key1', 'value1'), ('key2', 'value3')] res_post = requests.post('http://172.25.8.167:1080/post', data=parm) print(res_post.text) ''' 三、post請求 以json方式傳入參數 ''' url = 'http://172.25.8.167:1080/post' payload = {'some': 'data'} res_post = requests.post(url, data=json.dumps(payload)) print(res_post.text) ''' 四、post請求 將文件以參數的方式傳入 ''' url = 'http://172.25.8.167:1080/post' payload = {'file': open('report.xls', 'rb')} res_post = requests.post(url, data=json.dumps(payload)) print(res_post.text)
實例4:瞭解requests響應處理機制:測試
import requests parm = [('key1', 'value1'), ('key2', 'value3')] res_post = requests.post('http://172.25.8.167:1080/post', data=parm) print("\n以text格式處理返回響應結果", res_post.text) print("\n以json格式處理返回響應結果", res_post.json(), "\n") print("\n以二進制流格式處理返回響應結果", res_post.content, "\n") print("\n響應的URL:", res_post.url, "\n") print("\n響應的cookies:", res_post.cookies, "\n") print("\n響應的編碼:", res_post.encoding, "\n") print("\n響應的http狀態響應碼:", res_post.status_code, "\n") print("\n響應的header:", res_post.headers, "\n")
實例5:封裝(用於接口測試):網站
import requests class requests_run: ''' 封裝requests,用於接口測試 ''' def requests_post(self, url, data, header): if header != None: res = requests.post(url=url, headers=header, data=data) else: res = requests.post(url=url, data=data) return res def requests_get(self, url, data, header=None): if header != None: res = requests.get(url=url, headers=header, params=data) else: res = requests.get(url=url, params=data) return res def requests_main(self, url, method, data=None, header=None): if method == 'post': res = self.requests_post(url, data, header) else: res = self.requests_get(url, data, header) return res class Http_Request: ''' 更簡潔的封裝 ''' @staicmethod def http_request(self,url, data, method, header=None): if method = 'post': res = requests.post(url, data, header) else: res = requests.get(url, data, header) return res
實例5:結合Excel實現簡單的接口自動化編碼
from requests_demon4 import RequestsRun from with_excel import with_excel #以前寫的一個python讀取excel的類 import json csyl = with_excel('requests_test.xlsx','Sheet1') csyl_new = csyl.setnull_todict() for i in csyl_new: print(f'第{i["id"]}測試用例開始執行') # print(i["url"], i["method"], i["data"]) url = i["url"] method = i["method"] if i["data"] == '': data = None res = RequestsRun().requests_main(url, method) else: data = eval(i["data"]) res = RequestsRun().requests_main(url, method, data) print(f'第{i["id"]}測試用例結果爲:\n', json.dumps(res.json(), ensure_ascii=False, sort_keys=True, indent=2))
附:python讀取Excel的操做
1 import pandas as pd 2 3 path = 'test.xlsx' 4 sheet_name = 'test_data' 5 ''' 6 pd.read_excel(io, sheet_name=0, header=0, names=None, index_col=None, usecols=None) 7 io:很明顯, 是excel文件的路徑+名字字符串 8 sheet_name:返回指定的sheet 9 若是將sheet_name指定爲None,則返回全表 10 若是須要返回多個表, 能夠將sheet_name指定爲一個列表, 例如['sheet1', 'sheet2'] 11 name:若是沒有表頭, 可用此參數傳入列表作表頭 12 header:指定數據表的表頭,默認值爲0, 即將第一行做爲表頭 13 index_col:用做行索引的列編號或者列名,若是給定一個序列則有多個行索引。通常能夠設定index_col=False指的是pandas不適用第一列做爲行索引。 14 usecols:讀取指定的列, 也能夠經過名字或索引值 15 ''' 16 17 18 19 class with_excel: 20 21 #構造函數,調用類時就運行 22 def __init__(self, path=None, sheet_name=None): 23 if path and sheet_name: 24 self.path = path 25 self.sheet_name = sheet_name 26 else: 27 self.path = 'test.xlsx' 28 self.sheet_name = 'test_data' 29 self.data = self.open_excel() 30 31 #獲取表格數據 32 def open_excel(self): 33 df = pd.read_excel(self.path, self.sheet_name) 34 return df 35 36 #獲取表中單元格行數 37 def get_lines(self): 38 lines = self.data.shape[0]#獲取了最後一行的行數 39 return lines 40 41 #獲取一個單元格的內容(獲取多行的內容) 42 def get_cell_data(self, row, col): 43 return self.data.iloc[row, col] 44 45 #將表格數據轉字典 46 def to_dict(self): 47 test_data = [] 48 for i in self.data.index.values: # 獲取與表頭對應的字典數據 49 row_data = self.data.loc[i].to_dict() 50 test_data.append(row_data) 51 return test_data
總結:
利用python來作接口自動化,這裏的過程只是練手代碼而已,若是將這些代碼都熟練的掌握了,那我們就有作python接口自動化的基礎了。