python WEB介面自動化測試之requests庫詳解

來源:互聯網
上載者:User

標籤:getcwd   mon   cert   structure   dap   method   value   tar   raw   

1.Get請求 前提: requests庫是python的第三方庫,需要提前安裝哦,可以直接用pip命令:`python –m pip install requests` 按照慣例,先將requests庫的屬性列印出來,看看哪些屬性。 >>> import requests>>> dir(requests) #查看requests庫的屬性 [‘ConnectionError‘, ‘HTTPError‘, ‘NullHandler‘, ‘PreparedRequest‘, ‘Request‘, ‘RequestException‘, ‘Response‘, ‘Session‘, ‘Timeout‘, ‘TooManyRedirects‘, ‘URLRequired‘, ‘__author__‘, ‘__build__‘, ‘__builtins__‘, ‘__copyright__‘, ‘__doc__‘, ‘__file__‘, ‘__license__‘, ‘__name__‘, ‘__package__‘, ‘__path__‘, ‘__title__‘, ‘__version__‘, ‘adapters‘, ‘api‘, ‘auth‘, ‘certs‘, ‘codes‘, ‘compat‘, ‘cookies‘, ‘delete‘, ‘exceptions‘, ‘get‘, ‘head‘, ‘hooks‘, ‘logging‘, ‘models‘, ‘options‘, ‘packages‘, ‘patch‘, ‘post‘, ‘put‘, ‘request‘, ‘session‘, ‘sessions‘, ‘status_codes‘, ‘structures‘, ‘utils‘] 所以可以看到requests的屬性有get,post,delete,put,對應http請求的method方法。 常用的是get和post請求。get請求一般是查詢擷取資源資訊。post一般是更新資源資訊。  1.1查看get函數的使用  >>> help(requests.get) #查看requests庫的屬性get請求函數的使用 Help on function get in module requests.api: get(url, params=None, **kwargs) Sends a GET request. :param url: URL for the new :class:`Request` object.   :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response 1.2 requests的get函數的入參說明 url:調用介面的URL地址。 params:為選擇性參數,該參數是一個字典類型。資料會以鍵/值對的形式置於 URL 中,跟在一個問號的後面。舉例說明,若r=requests.get("http://httpbin.org/get",params={‘key1‘:‘value1‘,‘key2‘:‘value2‘}) 那麼,最終請求的目標URL為http://bin.org/get?key1=val1& key2=val2。  **kwargs:其他選擇性參數,例如headers,files,cookies,auth,timeout,json等。 例如:auth=(‘username,’password’):介面安全性測試中用到的使用者認證。 例如:headers = {‘user-agent‘: ‘my-app/0.0.1‘}:可定製發送要求標頭。 1.3 requests函數的傳回值(http響應) 返回的是response類對象(requests.models.Response)。來自requests模組 models.py裡的Response類 >>> r=requests.get(‘http://httpbin.org/get‘) #查看response的屬性 >>> dir(r) [‘__attrs__‘, ‘__bool__‘, ‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__getstate__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__module__‘, ‘__new__‘, ‘__nonzero__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setstate__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘_content‘, ‘_content_consumed‘, ‘apparent_encoding‘, ‘close‘, ‘connection‘, ‘content‘, ‘cookies‘, ‘elapsed‘, ‘encoding‘, ‘headers‘, ‘history‘, ‘is_permanent_redirect‘, ‘is_redirect‘, ‘iter_content‘, ‘iter_lines‘, ‘json‘, ‘links‘, ‘ok‘, ‘raise_for_status‘, ‘raw‘, ‘reason‘, ‘request‘, ‘status_code‘, ‘text‘,‘url‘]  對於返回對象常用的屬性如下: json():產生json資料對象的方法。如果 JSON 解碼失敗, r.json 就會拋出一個異常。例如,響應內容是 401 (Unauthorized),嘗試訪問 r.json 將會拋出 ValueError: No JSON object could be decoded 異常。  status_code:響應狀態代碼。 encoding:編碼,如utf-8。 url:目標url。 headers:回應標頭。類型為字典類型,若鍵不存在則返回None。 text:響應內容。字串方式,會自動根據回應標頭部的字元編碼進行解碼。如果你改變了編碼r.encoding,每當你訪問 r.text ,Request 都將會使用 r.encoding 的新值。  content:二進位響應內容。位元組方式,會自動為你解碼gzip和deflate壓縮。  raw:原始響應內容,也就是 urllib 的 response 對象,請求中要加stream=True,再使用 r.raw.read() 讀取。  r.raise_for_status:失敗請求(非200響應)拋出異常。  1.4 舉例說明  >>> payload={‘key1‘:‘value1‘,‘key2‘:‘value2‘} >>> r=requests.get("http://httpbin.org/get",params=payload) >>> r.status_code 200 >>> r.json() {u‘origin‘: u‘113.98.252.236‘, u‘headers‘: {u‘Host‘: u‘httpbin.org‘, u‘Accept-Encoding‘: u‘gzip, deflate‘, u‘Accept‘: u‘*/*‘, u‘User-Agent‘: u‘python-requests/2.7.0 CPython/2.7.11 Windows/7‘}, u‘args‘: {u‘key2‘: u‘value2‘, u‘key1‘: u‘value1‘}, u‘url‘: u‘http://httpbin.org/get?key2=value2&key1=value1‘} >>> r.url #url:params資料會以鍵/值對的形式置於 URL 中,跟在一個問號的後面。 u‘http://httpbin.org/get?key2=value2&key1=value1‘ >>> r.headers {‘content-length‘: ‘334‘, ‘server‘: ‘nginx‘, ‘connection‘: ‘keep-alive‘, ‘access-control-allow-credentials‘: ‘true‘, ‘date‘: ‘Fri, 09 Dec 2016 09:04:40 GMT‘, ‘access-control-allow-origin‘: ‘*‘, ‘content-type‘: ‘application/json‘} >>> r.headers[‘content-type‘] ‘application/json‘ >>> r.raw <requests.packages.urllib3.response.HTTPResponse object at 0x0000000002E64E10> >>> r.cookies <RequestsCookieJar[]> >>> r.text  u‘{\n "args": {\n "key1": "value1", \n "key2": "value2"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "origin": "113.98.252.236", \n "url": "http://httpbin.org/get?key2=value2&key1=value1"\n}\n‘ >>> r.content ‘{\n "args": {\n "key1": "value1", \n "key2": "value2"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "origin": "113.98.252.236", \n "url": "http://httpbin.org/get?key2=value2&key1=value1"\n}\n‘ >>> payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}  >>> r = requests.get("http://httpbin.org/get", params=payload,stream=True) >>> r.raw <requests.packages.urllib3.response.HTTPResponse object at 0x0000000003105940> >>> r.raw.read() ‘{\n "args": {\n "key1": "value1", \n "key2": "value2"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "origin": "113.98.252.236", \n "url": "http://httpbin.org/get?key2=value2&key1=value1"\n}\n‘  1.6 get請求總結 綜上所述,通過requests.get("某url",params={字典型別參數索引值對})類比瀏覽器發送一個http的請求(其中請求的方法是get,請求的url地址如下形式http://httpbin.org/get?key2=value2&key1=value1),伺服器處理資料後,會返回一個response對象,通過讀取response對象的屬性值,如json資料,可以做一系列的斷言,從而驗證該介面返回的資料是否正確。  2.POST請求  ## 2.1 查看post函數的使用 >>> help(requests.post) #查看requests庫的屬性post請求函數的使用 post(url, data=None, json=None, **kwargs) Sends a POST request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response  2.2 requests的post函數的入參說明 url:調用介面的URL地址。 data:為選擇性參數,該參數是一個字典類型。 json:為選擇性參數,該參數是一個json類型。 **kwargs:其他選擇性參數,例如headers等。  2.3 requests函數的傳回值(http響應)  同1.3 json():產生json資料對象的方法。如果 JSON 解碼失敗, r.json 就會拋出一個異常。例如,響應內容是 401 (Unauthorized),嘗試訪問 r.json 將會拋出 ValueError: No JSON object could be decoded 異常。  status_code:響應狀態代碼。 encoding:編碼,如utf-8。  url:目標url。  headers:回應標頭。類型為字典類型,若鍵不存在則返回None。 text:響應內容。字串方式,會自動根據回應標頭部的字元編碼進行解碼。如果你改變了編碼r.encoding,每當你訪問 r.text ,Request 都將會使用 r.encoding 的新值。  content:二進位響應內容。位元組方式,會自動為你解碼gzip和deflate壓縮。  raw:原始響應內容,也就是 urllib 的 response 對象,請求中要加stream=True,再使用 r.raw.read() 讀取。  r.raise_for_status:失敗請求(非200響應)拋出異常。   2.4舉例說明 >>> payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘} >>> r = requests.post("http://httpbin.org/post", data=payload)  >>> r.status_code 200  >>> r.json() {u‘files‘: {}, u‘origin‘: u‘113.98.252.236‘, u‘form‘: {u‘key2‘: u‘value2‘, u‘key1‘: u‘value1‘}, u‘url‘: u‘http://httpbin.org/post‘, u‘args‘: {}, u‘headers‘: {u‘Content-Length‘: u‘23‘, u‘Accept-Encoding‘: u‘gzip,deflate‘, u‘Accept‘: u‘*/*‘, u‘User-Agent‘: u‘python-requests/2.7.0 CPython/2.7.11 Windows/7‘, u‘Host‘: u‘httpbin.org‘, u‘Content-Type‘: u‘application/x-www-form-urlencoded‘}, u‘json‘: None, u‘data‘: u‘‘}  >>> r.url  u‘http://httpbin.org/post‘  >>> r.headers  {‘content-length‘: ‘461‘, ‘server‘: ‘nginx‘, ‘connection‘: ‘keep-alive‘, ‘access-control-allow-credentials‘: ‘true‘, ‘date‘: ‘Mon, 12 Dec 2016 02:46:14 GMT‘, ‘access-control-allow-origin‘: ‘*‘, ‘content-type‘: ‘application/json‘}  >>> r.headers[‘content-type‘]  ‘application/json‘  >>> r.raw  <requests.packages.urllib3.response.HTTPResponse object at 0x0000000002EE4A58>  >>> r.text u‘{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "key1": "value1", \n "key2": "value2"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Content-Length": "23", \n "Content-Type": "application/x-www-form-urlencoded", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "json": null, \n "origin": "113.98.252.236", \n "url": "http://httpbin.org/post"\n}\n‘ >>> r.content ‘{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "key1": "value1", \n "key2": "value2"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Content-Length": "23", \n "Content-Type": "application/x-www-form-urlencoded", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "json": null, \n "origin": "113.98.252.236", \n "url": "http://httpbin.org/post"\n}\n‘  >>> payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}  #擷取原始響應內容 >>> r = requests.post("http://httpbin.org/post", data=payload,stream=True) >>> r.raw <requests.packages.urllib3.response.HTTPResponse object at 0x0000000003105208> >>> r.raw.read() ‘{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "key1": "value1", \n "key2": "value2"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Content-Length": "23", \n "Content-Type": "application/x-www-form-urlencoded", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "json": null, \n "origin": "113.98.252.236", \n "url": "http://httpbin.org/post"\n}\n‘ #使用 json 參數直接傳遞 >>> payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘} >>> r = requests.post("http://httpbin.org/post", json=payload) >>> r.text u‘{\n "args": {}, \n "data": "{\\"key2\\": \\"value2\\", \\"key1\\": \\"value1\\"}", \n "files": {}, \n "form": {}, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Content-Length": "36", \n "Content-Type": "application/json", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "json": {\n "key1": "value1", \n "key2": "value2"\n }, \n "origin": "113.98.252.236", \n "url": "http://httpbi  3.其他用法 3.1 定製要求標頭 >>> payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘} >>> headers = {‘user-agent‘: ‘my-app/0.0.1‘} >>> r = requests.post("http://httpbin.org/post", data=payload,headers=headers)  3.2上傳檔案 >>> import os  >>> os.getcwd() ‘D:\\pythontest‘  >>> f=open(‘1.txt‘,‘w+‘)  >>> f.write(‘test‘) >>> os.listdir(‘D:\\pythontest‘)  [‘1.txt‘,]  >>> import requests >>> url = ‘http://httpbin.org/post‘  >>> files = {‘file‘: open(‘1.txt‘, ‘rb‘)} >>> r = requests.post(url, files=files) >>> r.text u‘{\n "args": {}, \n "data": "", \n "files": {\n "file": ""\n }, \n "form": {}, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Content-Length": "141", \n "Content-Type": "multipart/form-data; boundary=37de3eb22a754f34849771891b77bd23", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "json": null, \n "origin": "113.98.252.236", \n "url": "http://httpbin.org/post"\n}\n‘ 3.3 cookies的發送  >>> url = ‘http://httpbin.org/cookies‘ >>> cookies = dict(cookies_are=‘working‘) >>> r = requests.get(url, cookies=cookies) >>> r.text u‘{\n "cookies": {\n "cookies_are": "working"\n }\n}\n‘  4.知識拓展  4.1關於GET和POST的區別  GET請求的資料會附在URL之後(就是 把資料放置在HTTP協議頭中),以?分割URL和傳輸資料,參數之間以&相連,如:login.action?name=hyddd& password=idontknow&verify=%E4%BD%A0%E5%A5%BD。如果資料是英文字母/數字,原樣發送,如果是空格,轉換為+,如果是中文/其他字元,則直接把字串用BASE64加密,得出如:%E4%BD%A0%E5%A5%BD,其中%XX中的XX為該符號以 16進位表示的ASCII。  POST把提交的資料則放置在是HTTP包的包體中。  4.2關於請求的Headers的Accept-Encoding說明 請求的headers中的client項中的Accept-Encoding的,例如Accept-Encoding: gzip, deflate。瀏覽器申明自己接收的編碼方法,通常指定壓縮方法,是否支援壓縮,支援什麼壓縮方法(gzip,deflate)(注意:這不是隻字符編碼)。  4.3關於響應的Headers的Content-Type說明 Content-Type是返回訊息中非常重要的內容,表示後面的文檔屬於什麼MIME類型。  Content-Type: [type]/[subtype]; parameter。例如最常見的就是text/html,它的意思是說返回的內容是文本類型,這個文本又是HTML格式的。原則上瀏覽器會根據 Content-Type來決定如何顯示返回的訊息體內容。  ype有下面的形式: Text:用於標準化地表示的文本資訊,簡訊可以是多種字元集和或者多種格式的;  Multipart:用於串連訊息體的多個部分構成一個訊息,這些部分可以是不同類型的資料;  Application:用於傳輸應用程式資料或者位元據; Message:用於封裝一個E-mail訊息;  Image:用於傳輸靜態圖片資料; Audio:用於傳輸音頻或者音聲資料;  Video:用於傳輸動態影像資料,可以是與音頻編輯在一起的視頻資料格式。 subtype用於指定type的詳細形式。 parameter可以用來指定附加的資訊,更多情況下是用於指定text/plain和text/htm等的文字編碼方式的charset參數。  註:如果想要做好web自動化介面測試,必須要瞭解HTTP協議,想要瞭解更多HTTP協議,可查看HTTP協議詳解 轉自小坦克 4.4關於requests資料相關地址   文檔地址:http://docs.python-requests.org/en/master/ 中文文檔地址:http://cn.python-requests.org/zh_CN/latest/

python WEB介面自動化測試之requests庫詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.