慕运维2858188
2017-07-30 20:45:01浏览 11805
兼容性
try:
import cookielib # 兼容Python2
except:
import http.cookiejar as cookielib # python 3 need import http.cookiejar
创建 session
session = requests.session()
初始化创建cookies 对象
session.cookies = cookielib.LWPCookieJar(filename="cookies.txt") # LWP实例化的cookie可直接调用save方法
请求之前,装载cookies
session.cookies.load(ignore_discard=True)
session访问网址
response = session.get("https://www.imooc.com", headers=header) # more effective
登录成功后,将cookies 写入到指定文件中
session.cookies.save()
对cookie载入成功的判断
try:
session.cookies.load(ignore_discard=True)
print("Cookie正常加载")
except:
print("Cookie未能加载")