python 强国登录保存cookie,以后自动登录
from selenium import webdriver import os import time import json def browser_initial(): """" 进行浏览器初始化 """ os.chdir('D:\\') browser = webdriver.Chrome() log_url = 'https://pc.xuexi.cn/points/login.html' return log_url, browser def get_cookies(log_url, browser): """ 获取cookies保存至本地 """ browser.get(log_url) time.sleep(15) # 进行扫码登录 dictCookies = browser.get_cookies() # 获取list的cookies jsonCookies = json.dumps(dictCookies) # 转换成字符串保存 os.chdir('E:\qiangguo') with open('1.txt', 'a') as f: f.write(jsonCookies) print('cookies保存成功!') if __name__ == "__main__": tur = browser_initial() get_cookies(tur[0], tur[1])
from selenium import webdriver import json,os def browser_initial(): # 浏览器初始化,并打开学习强国界面(未登录状态,需扫码登录) browser = webdriver.Chrome() browser.get('https://pc.xuexi.cn/points/login.html') browser.maximize_window() return browser def log_xuexi(browser): """ 从本地读取cookies并刷新页面,成为已登录状态 """ os.chdir('E:\qiangguo') with open('1.txt', 'r', encoding='utf8') as f: listCookies = json.loads(f.read()) # 往browser里添加cookies for cookie in listCookies: cookie_dict = { 'domain': '.xuexi.cn', 'name': cookie.get('name'), 'value': cookie.get('value'), "expires": '', 'path': '/', 'httpOnly': False, 'HostOnly': False, 'Secure': False } browser.add_cookie(cookie_dict) browser.refresh() # 刷新网页,cookies才成功 if __name__ == "__main__": browser = browser_initial() # 浏览器初始化 log_xuexi(browser) # 读取本地cookie文本文件,写入浏览器,刷新网页查看是否登录成功