Cookie属性
name=value,健和值,具体的Cookie名称和内容
expires=xXXXXx,过期时间,Cookie的有效期
Path=/,根路径,Cookie作用的具体路径位置
HttpOnly,此Cookie只能服务器端修改,JS无法操作
requests.Session() # 自动更新cookie,适合频繁的请求
持久化Cookie
import requests
import json
cookies_dict = requests.utils.dict_from_cookiejar(session.cookies) # cookiejar转为dict
cookies_str = json.dumps(cookies_dict)
with open("cookies.txt", 'a', encoding='utf8') as file:
file.write(cookies_str)
file.write('\n')
session.cookies
是一个cookiejar
对象
装载Cookie
import requests
import json
with open("cookies.txt", 'r', encoding='utf8') as file:
cookies_list = file.readlines()
# session = requests.Session() # 不要一个session装载多个账号信息
for cookie_str in cookies_list:
cookie_dict = json.loads(cookie_str)
session = requests.Session()
session.cookies = requests.utils.cookiejar_from_dict(cookie_dict) # dict转cookiejar
response = session.get("http://shanzhi.spbeen.com/index/")
print(response, response.text)