如何用requests库在pytest中实现get请求接口自动化测试?

摘要:python中用于请求http接口的有自带的urllib和第三方库requests,但 urllib 写法稍微有点繁琐,所以在进行接口自动化测试过程中,一般使用更为简洁且功能强大的 requests 库。下面我们使用 requests 库发
python中用于请求http接口的有自带的urllib和第三方库requests,但 urllib 写法稍微有点繁琐,所以在进行接口自动化测试过程中,一般使用更为简洁且功能强大的 requests 库。下面我们使用 requests 库发送get请求。 requests库 简介 requests 库中提供对用的方法用于常用的HTTP请求,对应如下: requests.get() # 用于GET请求 requests.post() # 用于POST请求 requests.put() # 用于PUT请求 requests.delete() # 用于DELETE请求 当然还有更多的方法,这里只列举常用的。 安装 安装命令:pip install requests 发送get请求 get请求参数格式说明 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 send in the query string for 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) 参数说明: url,即接口地址 params,接口参数,可选(即可填可不填) **kwargs,可以添加其他请求参数,如设置请求头headers、超时时间timeout、cookies等 不带参数请求 import requests res = requests.get(url="https://www.cnblogs.com/lfr0123/") # 请求得到的res是一个Response对象,如果想要看到返回的文本内容,需要使用.text print(res.text) 带参数请求 import requests url = "http://www.baidu.com/s" params = {"wd": "给你一页白纸-博客园", "ie": "utf-8"} res = requests.get(url=url, params=params) print(res.text) 加入请求头headers 有些接口限制只能被浏览器访问,这时按照上面的代码去请求就会被禁止,我们可以在代码中加入 headers 参数伪装成浏览器进行接口请求,示例如下: import requests url = "http://www.baidu.com/s" params = {"wd": "给你一页白纸-博客园", "ie": "utf-8"} # User-Agent的值为浏览器类型 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36" } res = requests.get(url=url, params=params, headers=headers) print(res.text) 部分结果如下: 这里的响应体其实就是在百度中搜索给你一页白纸-博客园的结果页面。
阅读全文