1 requests模块发送请求
相关参考资料:
文档:Requests: 让 HTTP 服务人类 — Requests 2.18.1 文档
requests · PyPI:requests · PyPI
requests源码:GitH0ub - psf/requests: A simple, yet elegant, HTTP library.
HTTP协议相关:
安装:
pip install requests
1.1 发送get 请求
- 方法:requests.get()
- 参数传递:使用parmas传递参数
#导入 requess
#requests就是一个客户端,客户端是什么? 发送请求的一方,不一定有界面 前端、postman,user-agent
#python用requests发送请求其就是一个user-agent
#接收请求:服务端
import requests
#发送GET请求,需要传递参数,URL
url = "http://www.baidu.com"
res = requests.get(url)
#得到响应数据
"""
通过res获取其响应数据
"""
print(res) #<Response [200]>
print(res.status_code) #200
#获取返回的数据,获取文本
#方式一:返回HTML页面
print(res.text)
打印如图:
#方式二:二进制格式
#为字节流数据
#特殊情况:图片、视频、音频
print(res.content)
打印如图:
#打印为JSON格式的数据,返回的格式为字典
#返回的是字典,如果接口返回的不是json格式,res,json()报错
print(res.json())
#如果接口不是json的数据
#只能使用res.text,不然会报错
1.2 发送post 请求
- 方法:requests.post()
- 参数传递方式:
- application/x-www-form-urlencoded类型参数(表单类型):
- 使用data进行传递
- application/json类型参数(json类型):
- 使用json进行传递
- application/x-www-form-urlencoded类型参数(表单类型):
post和get即请求语句不相同,响应数据获取是一致的
res = requests.post(url)
print(res)
print(res.text)
print(res.content)
print(res.json())
1.2.1 常规用法
url = 'http://httpbin.org/post'
data = {'key1':'value1', 'key2':'value2'}
r =requests.post(url, data)
print(r)
print(r.text)
print(r.content)
"""结果
<Response [200]>
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.32.3",
"X-Amzn-Trace-Id": "Root=1-66cb4246-735d2da0745db93031d6070b"
},
"json": null,
"origin": "172.104.189.197",
"url": "http://httpbin.org/post"
}
b'{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "key1": "value1", \n "key2": "value2"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Content-Length": "23", \n "Content-Type": "application/x-www-form-urlencoded", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.32.3", \n "X-Amzn-Trace-Id": "Root=1-66cb4246-735d2da0745db93031d6070b"\n }, \n "json": null, \n "origin": "172.104.189.197", \n "url": "http://httpbin.org/post"\n}\n'
"""
1.2.2 JSON形式
1.3 发送patch请求
- 方法:requests.patch()
- 参数传递方式:
- application/x-www-form-urlencoded类型参数(表单类型):
- 使用data进行传递
- application/json类型参数(json类型):
- 使用json进行传递
- application/x-www-form-urlencoded类型参数(表单类型):
请求参数也可以使用字符串,但存在解析慢,存在数据格式不通用的场景,一般是通过字典形式来传递
2 响应数据的获取
- 方式一:text属性,自动识别编码方式进行编码
- data = response.text
- 方式二:content属性,需要 定要decode方法指定编码方式解码
- data = response.content.decode('utf8')
- 方式三:json方式,返回数据为json格式时,使用该方法来获取
- data = response.json()
- #查看完整的url print(res.url)
- #查看响应头部的字符编码 print(res.encoding)
- #查看响应码 print(res.status_code)
3 指定header设置
# 发送post请求
url = "http://httpbin.org/post"
user = {
"username": "python",
"password": "123456"
}
#headers不仅放type还可以放其他参数
headers = {
"content-type":"application/json"
}
# 如何发送query string
# 即使head设置为了json,但params也转换不到body中,params还是在url当中
res = requests.post(url, params=user, headers=headers)
#将参数放到body中
res = requests.post(url, data=user, headers=headers)
# form表单格式数据
print(res)
print(res.text)
print(res.content)
print(res.json())
"""结果
<Response [200]>
{
"args": {
"password": "123456",
"username": "python"
},
"data": "",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "0",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.32.3",
"X-Amzn-Trace-Id": "Root=1-66cb5487-0a111f6318caef86485e3568"
},
"json": null,
"origin": "172.104.189.197",
"url": "http://httpbin.org/post?username=python&password=123456"
}
b'{\n "args": {\n "password": "123456", \n "username": "python"\n }, \n "data": "", \n "files": {}, \n "form": {}, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Content-Length": "0", \n "Content-Type": "application/json", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.32.3", \n "X-Amzn-Trace-Id": "Root=1-66cb5487-0a111f6318caef86485e3568"\n }, \n "json": null, \n "origin": "172.104.189.197", \n "url": "http://httpbin.org/post?username=python&password=123456"\n}\n'
{'args': {'password': '123456', 'username': 'python'}, 'data': '', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '0', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.32.3', 'X-Amzn-Trace-Id': 'Root=1-66cb5487-0a111f6318caef86485e3568'}, 'json': None, 'origin': '172.104.189.197', 'url': 'http://httpbin.org/post?username=python&password=123456'}
"""
4 接口有鉴权怎么访问?
案例:请求需要登录才能访问的接口怎么办?
4.1 cookie + session 鉴权的接口处理?
使用requests.session对象来发送请求
session对象可以自动传递cookies信息(下一次请求会自动携带上次请求的cookies)
import requests
#创建session对象
sessio = requests.session()
步骤:先发请求登录,然后再请求需要鉴权的接口
import requests
s = requests.Session()
r = s.get('http://httpbin.org/cookies', cookies={'from-my':'browser'})
print(r.text)
"""结果
{
"cookies": {
"from-my": "browser"
}
}
"""
r = s.get('http://httpbin.org/cookies')
print(r.text)
"""结果
{
"cookies": {}
}
"""
#如果要手动添加cookie信息,可以属于Cookie Utility来操作
with requests.Session() as s:
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
httpbin 是一个使用 Python + Flask 编写的 HTTP HTTP Request & Response Service。,是一个开源项目。
主要用于测试 HTTP 库
4.2 使用token鉴权的接口处理?
登录之后,提取token,保存起来
请求需要鉴权的接口时,带上登录后提取的token
5 对requests模块进行二次封装
- 封装目的:
- 为了使用的时候更方便提高代码的重用率
- 封装的需求?
- 逻辑代码进行封装的方法,关键的数据参数化
- 哪些数据需要参数化?
- 请求地址、请求方法、请求参数
def simple(url,
params=None,
data=None,
json=None,
method='get',
**kwargs):
"""
封装接口
:return:字典 res.json()
"""
url = url
res = requests.request(method,
url ,
params = params,
data=data,
json = json,
**kwargs)
try:
return res.json()
except Exception as e:
logging.error("返回数据不是json格式:{}".format(e))
return res.text
return None