之前使用 requests 模块的时候,是直接 requests.get() 或者 requests.post() 发送GET请求或POST请求;当然也是可以带上 cookies 和 headers 的,但这都是一次性请求,你这次带着cookies信息,后面的请求还得带。这时候 requests.session() 就派上用场了,它可以自动处理cookies,做状态保持。
使用示例:
# 先实例化一个对象
session = requests.session()
# 后面用法和直接使用requests一样了
response = session.get(url) # get请求
response = session.post(url, json=json_data) # post请求
result = response.json()
使用实例:
比如登录抖音创作者平台,需要扫码授权
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",
'Referer': "https://creator.douyin.com/"
}
session = requests.session()
url = "https://sso.******.com/get_qrcode/?next=https:%2F%2Fcreator.douyin.com%2Fcreator-micro%2Fhome&aid=2906&service=https:%2F%2Fcreator.douyin.com&is_vcd=1&fp=ktv0uumo_gD7FPCuy_MfX7_44zL_9T1C_6i8sUgr4bDT6&_signature=_02B4Z6wo00101sT4NFgAAIDDp.L0MRPTY47E.DDAANCBkR36EPHb.UKQQDGsenolKJ1B9ZIKsRmMN1Lo5p4y-Shnacp.3qjY67FSttxF.sflFlqrTtdz3pJ8M3DCtlzB35tqqXl7pwkqcVr24c"
# 发起请求之前,我们可以打印一下session上下文请求对象里面的cookies
cookie_dict = requests.utils.dict_from_cookiejar(session.cookies)
print("======cookie_dict:", cookie_dict)
response = session.get(url, headers=headers)
result = response.json()
qrcode = result['data']['qrcode']
打印的结果:
======cookie_dict: {}
获取到base64类型的二维码之后,转为图片
def showBase64():
import base64
from PIL import Image
from io import BytesIO
base64_str = "iVBORw0KGgoAAAANSUhEUgAAAgAAAAIAAQMAAADOtka5AAAABlBMVEX///8AAABVwtN+AAAF10lEQVR42uydP5KsOAzG5SIg9BH6KD5aczSOwhEICSi0JX2SG5jel86gkrt2NpjnX02gsv59UlOePHny5MmTJ8+3w3qOcpSDaNiJBmbeaNxG5rWuRHWl1/LiRX4wz9RwY0pALID8KEdhPmjY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QgEhABwFCJFowPWIBhOhKbFbahMgOgS8QJiAeAtLBYeLEPn0CTAenbA1BJunaZEhAFcKCU1IUkNHqkSZCZ4rywOiABEQH0WSlTTD0wbKgeIPHUAGNxGYmJyt7XECUBvw/oa2EwBMIYDkSEAIKVhcmSxvk9JSAcgIiLDY1r09iWA2F6ANOBvXVM/h7c2s4JCABghlPogM+2MNsegGVhpiLR+OCWOCbg8QBMkVh0gF0iu8nKEB5onIjwwLaJ8E1UloAAAPIZUR0qQ8aApvG5b3y5/0OHkoDnA8SQUEQqPiy8m5qIal8i4Yoi+jlemIAQgNNUWdlteQAiDAsw6ko2W7g00xO9ExAQgDFT7TMNCDFcPlAtzLTEs+vO7/LEBPw+gBEn9tXAujNO64G9AoTiQRcH3vqNCYgAsKFxNIn6bmDMD6y9GojtAVpFarf6QQJiANhiA+sOYFX4yH1snHl9IU5cvGl8jRMTEAHQ5cK9bUyXnXG+NM42A5uM5L4tLAEhAGQyEt8dAEPSsjL0RKgomma8fVslmoBnA3ynrO6YRuJo4gG0jQWgAcZyahd++yqRBDwb4E0mTA/s5li0fkB9rAxbZU4y059fJZKAhwNs57yHGMM+bGe/Ur3F9OoLJO4JRwL+DMD2gKpQdGSvB5oqbEHG4G2in1MkCQgC0C8H+sQHNLoxacbQB0RBuCeeCYgA6FOiHwmJq4WrLYxfXq4eAOCLY0nAwwH9KyS4Tw+YNHDUGlLlU5uoWc/w6zcHJuDBgDx58uTJkydPpPNfAAAA///pJz5i3LPUMgAAAABJRU5ErkJggg=="
# 解码
result = base64.b64decode(base64_str)
print(result)
print(type(result))
# 将bytes结果转化为字节流
bytes_stream = BytesIO(result)
roiimg = Image.open(bytes_stream)
# roiimg.show()
imgByteArr = BytesIO() # 初始化一个空字节流
roiimg.save(imgByteArr, format('PNG')) # 把我们得图片以‘PNG’保存到空字节流
imgByteArr = imgByteArr.getvalue() # 无视指针,获取全部内容,类型由io流变成bytes
with open("abc.png", 'wb') as f:
f.write(imgByteArr)
手机扫码确认授权登录之后,我们再看下cookies信息
=== cookie_dict: {
'n_h': 'WGbUaxjyFD8F4IMOz-fEK6iA958s6jweL2yVh7I',
'passort_auth_status': '9ef800e1355e39af884d7b3e172b%2C',
'pasport_auth_status_ss': '9ef800e1355ede9af884d7b3e172b%2C',
'passort_csrf_token': '3f51c55b800f337b8281b70b68f1',
'pasport_csrf_token_default': '3f51c55b800f3327b8281b70b68f1',
'sesionid': '3806868312dd537a32b407d24bbe',
'sesionid_ss': '3806868312dd5379a32b407d24bbe',
'sid_uard': '3806868312dd537482b407d24bbe%7C1632657359%7C5184000%7CThu%2C+25-Nov-2021+11%3A55%3A59+GMT',
'sid_t': '3806868312dd537432b407d24bbe',
'sid_cp_v1': '1.0.0-KDY3NzI3MjUwOGhkOTZhMGMxNGNiY2I1ZThhYTczNzhjYzAyODkKFQj43Y-WnQMQz7_BigYY2hY4BkD0BxoCaGwiIDM4MDY4NjgzMTJkZDUzNzQ4NTlhMzJiNDA3ZDI0YmJl',
'ssid_cp_v1': '1.0.0-KDY3NzI3MGQwOThkOTZhMGMxNGNiY2I1ZThhYTczNzhjYzAyODkKFQj43Y-WnQMQz7_BigYY2hY4BkD0BxoCaGwiIDM4MDY4NjgzMTJkZDUzNzQ4NTlhMzJiNDA3ZDI0YmJl',
'sso_ud_tt': '64ec6781371386b133f88c6768d3',
'sso_ud_tt_ss': '64ec67813713859df33f88c6768d3',
'toutio_sso_user': '142588d2f1ea42c3841130987671',
'toutio_sso_user_ss': '142588d2f1fea42c3841130987671',
'uid_t': '0738744985dd4750fa23c564b6e5e',
'uid_t_ss': '0738744985dd4750fac3c564b6e5e'
}
可以看到,授权之后抖音的后台对这个请求设置了好多cookie(上图展示的cookie有删减),我们可以把这些cookies保存到字典,或者数据库,可以在cookie未过期的时候,继续拿着这些cookie请求登录过的接口。当然了,把字典的cookie设置到请求里面 session = requests.session() 也是很方便的,如下:
# 实例化对象
session = requests.session()
# 给 requests.session() 对象设置cookie信息
session.cookies = requests.utils.cookiejar_from_dict(cookies_dict)
# 下面还是拿着 session 去请求
session.post(url) 或者 session.get(url) 等等
有cookie设置过期时间的,可以获取cookie过期时间
@classmethod
def get_cookie_expires(cls, jar_cookies):
"""
获取 jar_cookies 里面 sessionid 或 sessionid_ss 或 sid_tt 的有效期
"""
result = None
for item in jar_cookies:
if item.name == "sessionid" or item.name == "sessionid_ss" or item.name == "sid_tt":
timestamp = item.expires
if timestamp:
result = cls.timestamp_to_datetime(timestamp)
return result
@staticmethod
def timestamp_to_datetime(timestamp):
"""
时间戳转datetime
:param timestamp:
:return: datetime
"""
result = datetime.fromtimestamp(timestamp)
return result
是不是感觉很好用,记录一下,如果能帮助到大家更好