# 登录页面操作 # page_objects/login_page.py from appium.webdriver.common.appiumby import AppiumBy from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException, NoSuchElementException import logging import time import globals.apis as apis import globals.ids as ids import globals.global_variable as global_variable # 导入全局变量模块 class LoginPage: def __init__(self, driver, wait): self.driver = driver self.wait = wait self.logger = logging.getLogger(__name__) def is_login_page(self): """检查当前是否为登录页面""" try: return self.driver.find_element(AppiumBy.ID, ids.LOGIN_BTN).is_displayed() except NoSuchElementException: return False def login(self): """执行登录操作""" try: self.logger.info("正在执行登录操作...") # 获取文本框中已有的用户名 username_field = self.wait.until( EC.element_to_be_clickable((AppiumBy.ID, ids.LOGIN_USERNAME)) ) # 读取文本框内已有的用户名(.text属性获取元素显示的文本内容) existing_username = username_field.text # 3. 将获取到的用户名写入全局变量中 # global_variable.GLOBAL_USERNAME = existing_username # 关键:给全局变量赋值 global_variable.set_username(existing_username) # 日志记录获取到的已有用户名(若为空,也需明确记录,避免后续误解) if existing_username.strip(): # 去除空格后判断是否有有效内容 self.logger.info(f"已获取文本框中的已有用户名: {existing_username}") else: self.logger.info("文本框中未检测到已有用户名(内容为空)") # 1. 定位密码输入框 password_field = self.wait.until( EC.element_to_be_clickable((AppiumBy.ID, ids.LOGIN_PASSWORD)) ) # 2. 清空密码框(如果需要) try: password_field.clear() # time.sleep(0.5) # 等待清除完成 except: # 如果clear方法不可用,尝试其他方式 pass accounts = apis.get_accounts_from_server("68c0dbfdb7cbcd616e7c5ab5") matches = [acc for acc in accounts if acc.get("username") == existing_username] if matches: password = matches[0].get("password") password_field.send_keys(password) # 4. 可选:隐藏键盘 try: self.driver.hide_keyboard() except: pass # 点击登录按钮 max_retries = 3 retry_count = 0 while retry_count < max_retries: login_btn = self.wait.until( EC.element_to_be_clickable((AppiumBy.ID, ids.LOGIN_BTN)) ) login_btn.click() self.logger.info(f"已点击登录按钮 (尝试 {retry_count + 1}/{max_retries})") # 等待登录完成 time.sleep(3) # 检查是否登录成功 if self.is_login_successful(): self.logger.info("登录成功") return True else: self.logger.warning("登录后未检测到主页面元素,准备重试") retry_count += 1 if retry_count < max_retries: self.logger.info(f"等待2秒后重新尝试登录...") time.sleep(2) self.logger.error(f"登录失败,已尝试 {max_retries} 次") return False except Exception as e: self.logger.error(f"登录过程中出错: {str(e)}") return False def is_login_successful(self): """检查登录是否成功""" try: # 等待主页面元素出现 self.wait.until( EC.presence_of_element_located((AppiumBy.ID, ids.DOWNLOAD_TABBAR_ID)) ) return True except TimeoutException: return False