1.判断应用程序元素是否存在,之前使用的代码如下,但是页面跳转后,通过xpath查找信息能查找到跳转前页面的内容,造成信息判断不准确。
def isElementPresent(self, driver, 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
于是更换判断方法,如下: 如果点击元素判断元素是否报错,判断页面跳转成功
1 @allure.step("判断元素是否可以点击") 2 def isElementCanClick(self, xpath, driver): 3 # 判断页面 4 flag = False 5 try: 6 driver.find_element_by_xpath(xpath).click() 7 flag = True 8 return flag 9 except: 10 return flag
问题重现
通过driver.page_source 查看可以取到的元素,再结合xpath检验