appium+selenium自动化测试UI踩坑记录之--判断元素是否存在

433 阅读1分钟

  判断应用程序元素是否存在,之前使用的代码如下,但是页面跳转后,通过xpath查找信息能查找到跳转前页面的内容,造成信息判断不准确。

          # 从selenium.common.exceptions 模块导入 NoSuchElementException类
          from selenium.common.exceptions import NoSuchElementException
          try:
              element = driver.find_element_by_xpath(xpath)
          # 原文是except NoSuchElementException, e:
          except NoSuchElementException as e:
              # 打印异常信息
              print(e)
              # 发生了NoSuchElementException异常,说明页面中未找到该元素,返回False
              return False
          else:
              # 没有发生异常,表示在页面中找到了该元素,返回True
              return True

  于是更换判断方法,如下: 如果点击元素判断元素是否报错,判断页面跳转成功

       def isElementCanClick(self, xpath, driver):
           # 判断页面
           flag = False
           try:
               driver.find_element_by_xpath(xpath).click()
               flag = True
               return flag
           except:
               return flag

  问题重现

  通过driver.page_source 查看可以取到的元素,再结合xpath检验