Python + Selenium 自动化登录及会话保持系统

系统功能说明

  1. 自动化登录功能

    • 自动填充用户名和密码

    • 支持手动输入验证码

    • 智能识别登录按钮并点击

  2. 会话管理

    • 定期刷新页面保持会话活跃

    • 自动检测登录状态

    • 发现登出后自动重新登录

  3. Cookie管理

    • 提取关键Admin-Token

    • 格式化为Bearer Token

    • 持久化存储到MySQL数据库

  4. 异常处理

    • 全面的错误捕获机制

    • 自动清理浏览器进程

    • 异常情况记录到数据库

  5. 用户行为模拟

    • 定时访问其他页面模拟真实用户

    • 随机间隔避免被识别为机器人

  6. from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    import MySQLdb
    import time
    from datetime import datetime
    import os
    
    class AutomatedLoginSystem:
        def __init__(self):
            # 初始化浏览器配置
            self.options = Options()
            self.options.add_experimental_option("detach", True)
            self.driver = None
    
        def get_db_connection(self):
            """获取数据库连接(示例配置)"""
            return MySQLdb.connect(
                host="your_database_host",
                user="your_username",
                password="your_password",
                database="your_database"
            )
    
        def save_cookie_to_db(self, cookies_string, current_time):
            """将Cookie存入数据库"""
            try:
                db = self.get_db_connection()
                cursor = db.cursor()
                
                # 清除旧Cookie
                cursor.execute("DELETE FROM auth_tokens WHERE token_type = 'admin'")
                
                # 插入新Cookie
                cursor.execute(
                    "INSERT INTO auth_tokens (token_type, token_value, created_at) VALUES (%s, %s, %s)",
                    ("admin", cookies_string, current_time)
                )
                
                db.commit()
                db.close()
                print("✅ 认证令牌已更新!", current_time)
            except Exception as e:
                print("数据库操作异常:", e)
    
        def is_logged_in(self):
            """检查登录状态"""
            try:
                welcome_element = WebDriverWait(self.driver, 5).until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, ".user-welcome"))
                )
                return "欢迎" in welcome_element.text
            except:
                return False
    
        def browse_other_pages(self):
            """模拟用户浏览行为"""
            try:
                # 示例页面跳转
                nav_links = self.driver.find_elements(By.CSS_SELECTOR, ".nav-link")
                for link in nav_links[:2]:  # 只访问前两个导航链接
                    link.click()
                    time.sleep(3)
            except Exception as e:
                print("页面跳转异常:", e)
    
        def get_auth_token(self):
            """获取认证令牌"""
            cookies = self.driver.get_cookies()
            auth_token = next(
                (cookie['value'] for cookie in cookies if cookie['name'] == 'Auth-Token'),
                None
            )
            return f"Bearer {auth_token}" if auth_token else None
    
        def login(self, username, password, login_url):
            """执行登录流程"""
            try:
                self.driver = webdriver.Chrome(options=self.options)
                self.driver.get(login_url)
    
                # 输入凭证
                WebDriverWait(self.driver, 10).until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, "input[name='username']"))
                ).send_keys(username)
                
                self.driver.find_element(
                    By.CSS_SELECTOR, "input[name='password']"
                ).send_keys(password)
    
                # 验证码处理
                print("请手动完成验证码验证...")
                WebDriverWait(self.driver, 120).until(
                    lambda driver: self.is_logged_in()
                )
    
                # 保存令牌
                if token := self.get_auth_token():
                    self.save_cookie_to_db(token, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                    return True
                return False
            except Exception as e:
                print("登录异常:", e)
                return False
    
        def maintain_session(self, username, password, login_url):
            """会话保持主循环"""
            while True:
                try:
                    time.sleep(300)  # 5分钟心跳
                    self.driver.refresh()
                    
                    if not self.is_logged_in():
                        print("会话失效,重新登录...")
                        self.driver.quit()
                        if not self.login(username, password, login_url):
                            break
                        continue
                    
                    self.browse_other_pages()
                    
                    if token := self.get_auth_token():
                        self.save_cookie_to_db(token, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                except Exception as e:
                    print("会话保持异常:", e)
                    self.save_cookie_to_db("SYSTEM_ERROR", datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    
    if __name__ == "__main__":
        auth_system = AutomatedLoginSystem()
        auth_system.login(
            username="your_username",
            password="your_password",
            login_url="https://example.com/login"
        )
        auth_system.maintain_session(
            username="your_username",
            password="your_password",
            login_url="https://example.com/login"
        )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值