场景:由于网络问题,或设备性能等问题,可能导致元素定位不稳定,使用显性等待方法可以提高元素定位的稳定性。使用页面对象模式(PO模式),
将显性等待方法与元素定位方法结合进行二次封装,以减少代码冗余和提高元素定位稳定性。
# /basePage.py from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.support.ui import WebDriverWait from appium.webdriver.common.mobileby import MobileBy as By class BasePage: def __init__(self, driver): self.driver = driver def get_visible_element(self, locator, timeout=5000): ''' 获取可视元素 param loctor: By方法定位元素,如(By.XPATH, "//*[@class='FrankTest']") return:返回可见元素 ''' try: return WebDriverWait(self.driver, timeout).until( ec.visibility_of_element_located(locator) ) except Exception as e: # 截图、日志 Screenshots(self.driver, "获取可视元素失败").screen_shot() log.error("获取可视元素失败:{}".format(e)) def get_presence_element(self, locator, timeout=5000): '''获取存在元素''' try: return WebDriverWait(self.driver, timeout).until( ec.presence_of_element_located(locator) ) except Exception as e: Screenshots(self.driver, "获取存在元素失败").screen_shot() log.error("获取存在元素失败:{}".format(e)) def get_clickable_element(self, locator, timeout=5000): '''获取可点击元素''' try: return WebDriverWait(self.driver, timeout).until( ec.element_to_be_clickable(locator) ) except Exception as e: Screenshots(self.driver, "获取可点击元素失败").screen_shot() log.error("可点击元素获取失败:{}".format(e))
以下示例调用新的定位方法来进行元素定位
from basePage import BasePage class loginPage(BasePage): account = (By.ID, 'account') password = (By.ID, 'password') login_btn = (By.XPATH, '//android.widget.TabWidget/android.widget.RelativeLayout[@index=1]') def login(self): '''输入账号密码进行登录''' get_visible_element(self.account).send_keys("Frank") get_visible_element(self.password).send_keys("123456") get_clickable_element(self.login_btn).click()
5000