API 接口自动化测试详细图文教程学习系列10--Requests模块2--举例说明

测试学习记录,仅供参考!

Requests 模块

Python requests库是一个常用的 Python HTTP客户端请求库,是一个简单易用、功能强大的库,特别适合用来与 RESTful API 进行交互,用于发送各种HTTP请求,如GET、POST、PUT、DELETE等,并处理返回的响应。使用 requests 库,开发者可以轻松地添加头部信息、发送表单数据、上传文件、管理会话、处理 Cookies 、使用代理等;它还可以支持 SSL 证书验证、连接超时设置、会话对象复用等高级功能。

三、Requests 模块发起接口请求

Requests 的基本使用

requests 的基本使用可以简单分为以下三个步骤;

  1. 导入模块,首先需要引入requests 模块;

  2. 其次是发送 http 请求(例如:get 请求),获取响应;

  3. 最后从响应信息中获取数据;

    引入相关模块,导入请求库

    import requests

    设置请求网址,发起HTTP请求,发送一个get请求,并把它赋值给变量response

    response = requests.get('https://www.baidu.com/')

    获取打印响应数据

    print(response.text)

    打印输出结果

    <!DOCTYPE html> <html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>ç™¾åº¦ä¸€ä¸‹ï¼Œä½ å°±çŸ¥é“</title></head> <body link=#0000cc>
    <form id=form name=f action=//www.baidu.com/s class=fm> </form>
    新é—>> hao123 地图 视频 贴吧 <noscript> ç™>>录 </noscript> <script>document.write('ç™>>录');
    复制代码
                 </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必è¯>></a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

    进程已结束,退出代码为 0

从打印输出结果中可以发现输出的结果包含了一些特殊的字符,如ç¾åº¦ä¸ä¸ï¼äå°è´´å>>å½,这些字符实际上是UTF-8编码的中文字符,由于在命令提示符中没有正确显示,所以看起来像是乱码。

复制代码
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>ç™¾åº¦ä¸€ä¸‹ï¼Œä½ å°±çŸ¥é“</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新é—>></a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç™>>录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">ç™>>录</a>');
                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必è¯>></a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>


进程已结束,退出代码为 0
查看所使用编码

如果要想知道自已所使用的是什么编码,直接使用 response.encoding 方法;

复制代码
# 导入请求库
import requests
# 设置请求网址
response = requests.get("https://www.baidu.com/") 
# 输出信息
print(response.text)
# 获取编码
print(response.encoding)


# 输出结果
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>ç™¾åº¦ä¸€ä¸‹ï¼Œä½ å°±çŸ¥é“</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新é—>></a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç™>>录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">ç™>>录</a>');
                                                                                                                                                                                                                                                                                                                                                                 </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必è¯>></a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

ISO-8859-1

进程已结束,退出代码为 0

可以看到所使用的编码格式是"ISO-8859-1";

ISO-8859-1,也称为Latin-1,是一种单字节字符集编码,它是为了表示西欧语言中的大部分字符而设计的。这种编码标准是国际标准化组织(ISO)在1987年制定的,它是ISO 8859系列字符集编码中的第一个成员。ISO-8859-1编码可以表示256个不同的字符,包括英文字母(大写和小写)、数字、标点符号以及一些特殊符号。此外,它还包括西欧语言中的特殊字符,如法语的ç、é、è、ê、ë,德语的ä、ö、ü,以及西班牙语的ñ等。在计算机和网络技术中,ISO-8859-1曾经被广泛用作默认的字符编码,特别是在早期的互联网和电子邮件系统中。然而,随着多语言互联网内容的增长,这种编码逐渐被更通用的Unicode编码(如UTF-8)所取代,因为Unicode能够表示世界上大多数语言的字符,而ISO-8859-1仅限于西欧语言。

在HTML文档中,可以通过<meta charset="ISO-8859-1">标签来指定使用ISO-8859-1字符集。在HTTP头部信息中,也可以通过Content-Type字段来指定字符编码,例如:Content-Type: text/html; charset=ISO-8859-1。

设置编码格式,解决乱码

要想把我们的所获取的乱码变为中文字符,只需要设置编码为UTF-8即可;

复制代码
# 一般初始默认是GBK编码格式
response.encoding='gbk'
# 自定义设置为UTF-8编码格式
response.encoding='utf-8'

优化设置编码格式为 UTF-8 ;

复制代码
# 导入请求库
import requests
# 设置请求网址
response = requests.get('https://www.baidu.com/') 
# 设置编码
response.encoding = 'utf8'
# 输出信息
print(response.text)


# 打印输出结果
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>


进程已结束,退出代码为 0

对比查看打印输出结果;

复制代码
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>


进程已结束,退出代码为 0

Requests 的各种请求方式

最常用的就是 requests.get() 和 requests.post() ;

复制代码
import requests
r = requests.get('https://api.github.com/events')
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
r = requests.put('http://httpbin.org/put', data = {'key':'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')

|--------------------|---|---|
| 示例 | 描述 ||
| requests.request() | 构造一个请求,最基本的方法 ||
| requests.get() | 用于从服务器获取资源,可以携带查询参数;获取网页,对应HTTP中的GET方法 ||
| requests.post() | 向网页/服务器提交数据信息,可以携带表单数据/JSON数据;对应HTTP中的POST方法 ||
| requests.put() | 用于向服务器上传文件或替换指定的资源;向html提交put方法,对应HTTP中的PUT方法 ||
| requests.delete() | 用于删除指定的资源;向html提交删除请求,对应HTTP中的DELETE方法 ||
| requests.head() | 用于获取头部信息,不返回响应体;获取html网页的头信息,对应HTTP中的HEAD方法 ||
| requests.options() | 用于查询服务器支持的HTTP方法 ||
| requests.patch() | 向html网页提交局部请求修改的的请求,对应HTTP中的PATCH方法 ||

响应结果 response

response 常见属性
其他
复制代码
import requests
respone=requests.get('http://www.jianshu.com')
# respone属性
print(respone.text)
print(respone.content)
print(respone.status_code)
print(respone.headers)
print(respone.cookies)
print(respone.cookies.get_dict())
print(respone.cookies.items())
print(respone.url)
print(respone.history)
print(respone.encoding)
#关闭:response.close()
from contextlib import closing
with closing(requests.get('http://www.jianshu.com',stream=True)) as response:
    for line in response.iter_content():
        pass

<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>openresty</center>
</body>
</html>

b'<html>\r\n<head><title>403 Forbidden</title></head>\r\n<body>\r\n<center><h1>403 Forbidden</h1></center>\r\n<hr><center>openresty</center>\r\n</body>\r\n</html>\r\n'
403
{'Date': 'Tue, 07 Apr 2026 20:18:12 GMT', 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Vary': 'Accept-Encoding', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'Content-Encoding': 'gzip'}
<RequestsCookieJar[]>
{}
[]
https://www.jianshu.com/
[<Response [302]>]
ISO-8859-1

进程已结束,退出代码为 0

其他烦请自行学习了解。

复制代码
# 把二进制数据转换字符串
print(response.content.decode())
# 在方法内部判断resp.status_code是否等于200,如果不等于,则抛出异常
response.raise_for_status() 	
# 从内容中分析出的响应内容编码方式(备选编码方式)
response.apparent_encoding    
# 得到对应的 json 格式的数据,类似于字典
response.json()	

未完待续。。。

相关推荐
SunnyDays10112 小时前
Python 如何实现 Markdown 与 Excel 互转
python·excel转markdown·markdown转excel·markdown转xlsx
CHU7290352 小时前
在线教学课堂APP功能版块设计方案:重构学习场景的交互逻辑
java·学习·小程序·重构
嵌入式-小王2 小时前
LangChain框架(二)---- 提示词模板
python·langchain
克里普crirp2 小时前
北斗电离层模型BDGIM广播系数
开发语言·python
深度学习lover2 小时前
<数据集>yolo扑克牌识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·扑克牌识别
迷藏4942 小时前
**发散创新:基于 Rust的模型保护机制设计与实践**在人工智能快速发
java·人工智能·python·rust·neo4j
kcuwu.2 小时前
从Python\+MySQL到Redis:非关系型数据库详解(PyCharm实操版)
redis·python·mysql
一定要AK2 小时前
HTML5 入门到精通全章节学习笔记
笔记·学习·html5
程序员zgh2 小时前
C/C++ 单元测试系统 构建
c语言·开发语言·c++·学习·单元测试