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檢驗
