Cookie属性

  1. name=value,健和值,具体的Cookie名称和内容
  2. expires=xXXXXx,过期时间,Cookie的有效期
  3. Path=/,根路径,Cookie作用的具体路径位置
  4. HttpOnly,此Cookie只能服务器端修改,JS无法操作

requests.Session() # 自动更新cookie,适合频繁的请求

持久化Cookie

  1. import requests
  2. import json
  3. cookies_dict = requests.utils.dict_from_cookiejar(session.cookies) # cookiejar转为dict
  4. cookies_str = json.dumps(cookies_dict)
  5. with open("cookies.txt", 'a', encoding='utf8') as file:
  6. file.write(cookies_str)
  7. file.write('\n')

session.cookies是一个cookiejar对象

装载Cookie

  1. import requests
  2. import json
  3. with open("cookies.txt", 'r', encoding='utf8') as file:
  4. cookies_list = file.readlines()
  5. # session = requests.Session() # 不要一个session装载多个账号信息
  6. for cookie_str in cookies_list:
  7. cookie_dict = json.loads(cookie_str)
  8. session = requests.Session()
  9. session.cookies = requests.utils.cookiejar_from_dict(cookie_dict) # dict转cookiejar
  10. response = session.get("http://shanzhi.spbeen.com/index/")
  11. print(response, response.text)