UI自动化-针对验证码登录的系统,通过首次手动登录存储cookie的方式后续访问免登录方法

1. 保存登录信息脚本(仅需执行 1 次)

代码作用:打开浏览器,等待手动完成登录后,自动把所有 Cookie、LocalStorage、SessionStorage 保存到本地 JSON 文件,拿到完整的登录上下文

python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json

# 1. 配置Chrome(保留登录上下文)
chrome_options = Options()
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])  # 隐藏Selenium的自动化标识,避免被网站检测到是机器人操作
driver = webdriver.Chrome(options=chrome_options)  # 用自定义配置初始化Chrome浏览器驱动

# 2. 打开登录页,等待你手动登录
driver.get("https://app.test.com")
input("请在浏览器中完成登录,登录成功后按回车键继续...")

# 3. 保存所有登录上下文(核心:完整获取,不遗漏任何字段)
login_info = {
    "cookies": driver.get_cookies(),  # 保存所有Cookie(含TDC_token等)
    "local_storage": {},
    "session_storage": {}
}

# 3.1 保存LocalStorage所有键值对
local_storage_keys = driver.execute_script("return Object.keys(localStorage);")
for key in local_storage_keys:
    login_info["local_storage"][key] = driver.execute_script(f"return localStorage.getItem('{key}');")

# 3.2 保存SessionStorage所有键值对
session_storage_keys = driver.execute_script("return Object.keys(sessionStorage);")
for key in session_storage_keys:
    login_info["session_storage"][key] = driver.execute_script(f"return sessionStorage.getItem('{key}');")

# 4. 写入本地JSON文件(持久化保存)
with open("qimi_login_info.json", "w", encoding="utf-8") as f:
    json.dump(login_info, f, ensure_ascii=False, indent=2)

print("登录信息已完整保存到login_info.json")
driver.quit()
sleep(3)

2. 读取登录信息免登录脚本(可重复执行)

作用:读取本地保存的登录信息,一键注入浏览器,实现免登录,无需手动输入账号密码

python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import json
import time
from time import sleep

# 1. 配置Chrome(禁止新窗口、保留上下文)
chrome_options = Options()
chrome_options.add_argument("--disable-popup-blocking")  # 禁止弹窗
chrome_options.add_argument("--new-window=0")  # 禁止新窗口
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])  # 隐藏自动化标识
driver = webdriver.Chrome(options=chrome_options)

# 2. 先进入目标域名上下文(关键:避免Storage禁用错误)
driver.get("https://app.test.com")
time.sleep(2)

# 3. 读取本地保存的登录信息
with open("login_info.json", "r", encoding="utf-8") as f:
    login_info = json.load(f)

# 4. 注入所有登录上下文(按顺序:Cookie → LocalStorage → SessionStorage)
# 4.1 注入Cookie(逐个添加,确保完整)
for cookie in login_info["cookies"]:
    # 修复Cookie的expiry类型(避免Selenium报错)
    if "expiry" in cookie and isinstance(cookie["expiry"], float):
        cookie["expiry"] = int(cookie["expiry"])
    driver.add_cookie(cookie)

# 4.2 注入LocalStorage
for key, value in login_info["local_storage"].items():
    driver.execute_script(f"localStorage.setItem({json.dumps(key)}, {json.dumps(value)});")

# 4.3 注入SessionStorage
for key, value in login_info["session_storage"].items():
    driver.execute_script(f"sessionStorage.setItem({json.dumps(key)}, {json.dumps(value)});")

print("所有登录信息已注入,正在进入目标页面...")

# 5. 访问目标页面(同一窗口,上下文不丢失)
driver.get("https://app.test.com/Home")

# 6. 验证是否登录成功(显式等待,避免空白页误判)
try:
    # 等待首页关键元素加载(替换为你页面的实际元素)
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.XPATH, '//*[contains(text(),"首页") or contains(@class,"user-name")]'))
    )
    print("免登录成功!已进入Home页面")
except Exception as e:
    print(f"免登录失败,原因:{e}")
    driver.save_screenshot("login_fail.png")

# 保持浏览器打开
input("按回车键关闭浏览器...")
driver.quit()
相关推荐
hcnaisd22 小时前
使用Python进行PDF文件的处理与操作
jvm·数据库·python
weixin_458923202 小时前
分布式日志系统实现
开发语言·c++·算法
开发者小天2 小时前
python中calss的用法
开发语言·python
weixin_462446232 小时前
使用 Python 批量在 HTML 文件中插入自定义 div 元素
python·beautifulsoup·自动化脚本·html 批量处理
沉默-_-2 小时前
MyBatis 学习笔记
java·开发语言·tomcat
会游泳的石头2 小时前
构建企业级知识库智能问答系统:基于 Java 与 Spring Boot 的轻量实现
java·开发语言·spring boot·ai
m0_748229992 小时前
Laravel4.x核心更新全解析
开发语言·php
SeatuneWrite2 小时前
**AI漫剧软件2025推荐,解锁沉浸式二次元内容创作新体验
大数据·人工智能·python
j_xxx404_2 小时前
C++算法入门:滑动窗口合集(长度最小的子数组|无重复字符的最长字串|)
开发语言·c++·算法