测试学习记录,仅供参考!
Requests 模块
Python requests库是一个常用的 Python HTTP客户端请求库,是一个简单易用、功能强大的库,特别适合用来与 RESTful API 进行交互,用于发送各种HTTP请求,如GET、POST、PUT、DELETE等,并处理返回的响应。使用 requests 库,开发者可以轻松地添加头部信息、发送表单数据、上传文件、管理会话、处理 Cookies 、使用代理等;它还可以支持 SSL 证书验证、连接超时设置、会话对象复用等高级功能。
三、Requests 模块发起接口请求
Requests 的基本使用
requests 的基本使用可以简单分为以下三个步骤;
-
导入模块,首先需要引入requests 模块;
-
其次是发送 http 请求(例如:get 请求),获取响应;
-
最后从响应信息中获取数据;
引入相关模块,导入请求库
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>©2017 Baidu <a href=http://www.baidu.com/duty/>使ç¨ç¾åº¦åå¿ è¯>></a> <a href=http://jianyi.baidu.com/ class=cp-feedback>æè§åé¦</a> 京ICPè¯030173å· <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&tpl=mn&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>©2017 Baidu <a href=http://www.baidu.com/duty/>使ç¨ç¾åº¦åå¿ è¯>></a> <a href=http://jianyi.baidu.com/ class=cp-feedback>æè§åé¦</a> 京ICPè¯030173å· <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&tpl=mn&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>©2017 Baidu <a href=http://www.baidu.com/duty/>使ç¨ç¾åº¦åå¿ è¯>></a> <a href=http://jianyi.baidu.com/ class=cp-feedback>æè§åé¦</a> 京ICPè¯030173å· <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&tpl=mn&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>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <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&tpl=mn&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>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html> 进程已结束,退出代码为 0Requests 的各种请求方式
最常用的就是 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 常见属性
-
response.text : 响应体 str 类型
-
response.ecoding : 二进制转换字符使用的编码
-
respones.content: 响应体 bytes类型
import requests
response=requests.get('http://www.baidu.com')respone属性
获取解码后的内容 html -- 响应体--转成了字符串形式
print(response.text)
获取二进制字节数据 -- 响应体--二进制(图片,视频)
print(response.content)
响应状态码
print(response.status_code)
响应头
print(response.headers)
响应的cookie--服务端返回的cookies
print(response.cookies)
返回cookiejar类型对象--转成字典格式
print(response.cookies.get_dict())
cookie的value值
print(response.cookies.items())
当次请求的地址
print(response.url)
访问历史--需要重定向才会有 -- 如果有重定向,放到一个列表中
print(response.history)
响应体--编码格式
print(response.encoding)
打印输出结果
<!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=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é</title></head> <body link=#0000cc></body> </html>©2017 Baidu 使ç¨ç¾åº¦åå¿ è¯>> æè§åé¦ äº¬ICPè¯030173å·
b'<!DOCTYPE html>\r\n<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=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title></head> <body link=#0000cc>
</body> </html>\r\n'<form id=form name=f action=//www.baidu.com/s class=fm> </form>
\xe6\x96\xb0\xe9\x97\xbb hao123 \xe5\x9c\xb0\xe5\x9b\xbe \xe8\xa7\x86\xe9\xa2\x91 \xe8\xb4\xb4\xe5\x90\xa7 <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F%3Fbdorz_come%3D1 name=tj_login class=lb>\xe7\x99\xbb\xe5\xbd\x95 </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">\xe7\x99\xbb\xe5\xbd\x95');</script> \xe6\x9b\xb4\xe5\xa4\x9a\xe4\xba\xa7\xe5\x93\x81\xe5\x85\xb3\xe4\xba\x8e\xe7\x99\xbe\xe5\xba\xa6 About Baidu
©2017 Baidu \xe4\xbd\xbf\xe7\x94\xa8\xe7\x99\xbe\xe5\xba\xa6\xe5\x89\x8d\xe5\xbf\x85\xe8\xaf\xbb \xe6\x84\x8f\xe8\xa7\x81\xe5\x8f\x8d\xe9\xa6\x88 \xe4\xba\xacICP\xe8\xaf\x81030173\xe5\x8f\xb7
200
{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Content-Encoding': 'gzip', 'Content-Length': '1108', 'Content-Type': 'text/html', 'Pragma': 'no-cache', 'Server': 'bfe', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Date': 'Tue, 07 Apr 2026 20:05:19 GMT'}
<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
{'BDORZ': '27315'}
[('BDORZ', '27315')]
http://www.baidu.com/
[]
ISO-8859-1进程已结束,退出代码为 0
其他
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()未完待续。。。
-