python环境,将requests的cookie保存到本地,再次启动时从本地载入cookie
时间: 2023-04-04 16:03:19 浏览: 189
Python 如何通过requests模块实现Cookie登录 Python源码
可以使用pickle模块将cookie对象序列化保存到本地文件中,再次启动时使用pickle模块反序列化读取本地文件中的cookie对象即可。具体代码如下:
import pickle
import requests
# 保存cookie到本地文件
def save_cookie(cookie, filename):
with open(filename, 'wb') as f:
pickle.dump(cookie, f)
# 从本地文件中读取cookie
def load_cookie(filename):
with open(filename, 'rb') as f:
cookie = pickle.load(f)
return cookie
# 发送请求并保存cookie
url = 'http://www.example.com'
response = requests.get(url)
cookie = response.cookies
save_cookie(cookie, 'cookie.txt')
# 从本地文件中读取cookie并发送请求
cookie = load_cookie('cookie.txt')
headers = {'cookie': cookie}
response = requests.get(url, headers=headers)
print(response.text)
阅读全文