requests---requests简介
在做接口測試的時候都會用到很多工具,如postman、jmeter、soupUI等工具,除了這些工具外,我們也可以用python的第3方庫requests來做接口測試。
?
request簡介
requests是python實現的簡單易用的HTTP庫,屬于python的第3方庫,通過pip進行安裝使用。
requests中文文檔:https://2.python-requests.org//zh_CN/latest/user/quickstart.html#
requests安裝
1.打開cmd
2.通過pip進行安裝
# 安裝requests pip install requests?
requests發送get請求
源碼:
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 sendin 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模塊
2.選擇get方法請求地址:https://www.cnblogs.com/qican/
3.可以查看請求的返回內容
# coding:utf-8 # 導入模塊 import requests # 請求地址 url = 'https://www.cnblogs.com/qican/'r = requests.get(url) # 請求返回內容 text = r.text print(text)
4.請求攜帶參數params
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
?
requests請求post
源碼:
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-likeobject 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格式?
轉載于:https://www.cnblogs.com/qican/p/11153054.html
總結
以上是生活随笔為你收集整理的requests---requests简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法两数相加
- 下一篇: 顺序表的结构和9个基本运算算法