app自动化——弹窗异常处理

黑名单处理

  • 运行过程中不定时弹框(广告弹窗,升级提示框,新消息提示框等等)
  • 弹框不是 BUG(UI 界面提示,警告的作用)

方法一:常规处理

def find(self, by, locator):
    try:
        return self.driver.find_element(by, locator)
    except Exception as e:
        for black in black_list:
            eles = self.driver.find_elements(*black)
            if len(eles) > 0:
                eles[0].click()
                return find(by, locator)
        raise e

方法二:装饰器处理

装饰器的优势

  • 对原有函数的功能增强
  • 不改变原有函数的逻辑
  • 使代码更简洁、易维护

__BLACK_LIST = []

def black_handle(func):
    """黑名单处理机制"""
    def _inner(*args, **kwargs):
        inner_arg = args[0]
        try:
            func(*args, **kwargs)
            # logger.info(f"查找元素:{locator}--->成功")
        except Exception as e:
            logger.info("未找到元素")
            logger.info(f"异常信息:{e}")
            logger.info("处理异常")
            for i in __BLACK_LIST:
                elements = inner_arg.driver.find_elements(*i)
                if len(elements) > 0:
                    elements[0].click()
                    return func(*args, **kwargs)
            raise e

    return _inner

装饰函数或方法

@black_handle
def do_find(self, locator: tuple):
        """获取单个元素"""
        element = self.driver.find_element(*locator)
        logger.info(f"查找元素:{locator}--->成功")
        return element