import subprocess import time from selenium import webdriver from selenium.webdriver.edge.service import Service from selenium.webdriver.edge.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 # 参数配置 PING_HOST = "www.baidu.com" USERNAME = "" # 在引号内填写账号 PASSWORD = "" # 在引号内填写密码 CHECK_INTERVAL = 60 # 每60秒ping一次,监测网络连接 DISCONNECT_THRESHOLD = 300 # 断网300秒后尝试自动连接 options = Options() options.add_argument("--headless") # 无头模式 options.add_argument("--disable-gpu") options.add_argument("--no-sandbox") options.add_argument("--disable-blink-features=AutomationControlled") service = Service() # 若未配置 PATH,这里填写 msedgedriver.exe 路径 def is_network_ok(): """判断网络是否可用,ping百度测试""" try: result = subprocess.run( ["ping", "-n" if subprocess.os.name == "nt" else "-c", "1", PING_HOST], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) return result.returncode == 0 except: return False def perform_login(): """执行自动认证流程(无头浏览器)""" driver = None try: driver = webdriver.Edge(service=service, options=options) wait = WebDriverWait(driver, 30) driver.get("http://10.33.0.2") # 输入账号 username_input = wait.until( EC.presence_of_element_located((By.ID, "username")) ) username_input.clear() username_input.send_keys(USERNAME) # 输入密码 password_input = driver.find_element(By.ID, "password") password_input.clear() password_input.send_keys(PASSWORD) print("已输入<账号密码>") # 点击登录 login_btn = wait.until( EC.element_to_be_clickable((By.ID, "login-account")) ) login_btn.click() print("已点击<登录>") # 等待“代拨成功”弹窗 success_confirm = wait.until( EC.element_to_be_clickable((By.CLASS_NAME, "btn-confirm")) ) success_confirm.click() print("<代拨成功>") time.sleep(3) except Exception as e: print(f"登录过程中出现异常: {e}") finally: if driver: driver.quit() # 确保浏览器关闭 def main(): disconnect_time = 0 try: while True: if is_network_ok(): disconnect_time = 0 print("网络正常") else: disconnect_time += CHECK_INTERVAL print(f"网络中断 {disconnect_time} 秒") if disconnect_time >= DISCONNECT_THRESHOLD: print("断网超时,自动认证...") perform_login() disconnect_time = 0 # 重置计时 time.sleep(CHECK_INTERVAL) except KeyboardInterrupt: print("\n用户终止程序,退出中...") if __name__ == "__main__": main()