在作接口測試的時候都會用到不少工具,如postman、jmeter、soupUI等工具,除了這些工具外,咱們也能夠用python的第3方庫requests來作接口測試。html
requests是python實現的簡單易用的HTTP庫,屬於python的第3方庫,經過pip進行安裝使用。python
requests中文文檔:https://2.python-requests.org//zh_CN/latest/user/quickstart.html#json
1.打開cmdapi
2.經過pip進行安裝cookie
# 安裝requests
pip install requests
源碼:工具
def get(url, params=None, **kwargs): r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return request('get', url, params=params, **kwargs)
1.首先導入requests模塊post
2.選擇get方法請求地址:https://www.cnblogs.com/qican/測試
3.能夠查看請求的返回內容ui
# coding:utf-8 # 導入模塊 import requests # 請求地址 url = 'https://www.cnblogs.com/qican/'
r = requests.get(url) # 請求返回內容 text = r.text print(text)
4.請求攜帶參數paramsurl
5.請求地址:http://httpbin.org/get?
6.請求參數書寫以字典形式編寫如{ "name": "requests" }
# coding:utf-8 # 導入requests模塊 import requests # 攜帶參數 params = { "name": "request", "name1":"python" } # 請求地址 url = 'http://httpbin.org/get?' r = requests.get(url,params=params) text = r.text print(text)
代碼結果: { "args": { "name": "requests", "name1": "python" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.21.0" }, "origin": "116.247.112.151, 116.247.112.151", "url": "https://httpbin.org/get?name=requests&name1=python" }
經過觀察,能夠發現最後的url地址已經被更改爲了name=requests和name1=python
源碼:
def post(url, data=None, json=None, **kwargs): r"""Sends a POST request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, 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 """ return request('post', url, data=data, json=json, **kwargs)
1.導入requests模塊
2.選擇post方法請求:http://apis.juhe.cn/simpleWeather/query
3.輸入參數格式{」name「:」value「}
# coding:utf-8 import requests # 導入模塊 url = 'http://apis.juhe.cn/simpleWeather/query' # 請求地址 # 請求參數 data = { "city":"上海", "key":"331eab8f3481f37868378fcdc76cb7cd" } r = requests.post(data=data,url=url) print(r.text)
r.text # 返回所有內容 r.url # 返回的url地址 r.content # 返回解碼後的內容 r.cookies # 返回cookies r.headers # 返回攜帶的請求頭 r.status_code # 返回狀態碼 r.json() # 返回json格式