Selenium中沒有提供原生的方法判斷元素是否存在,一般我們可以通過定位元素+異常捕獲的方式判斷。Python示例代碼如下:
from selenium.common.exceptions import NoSuchElementException # 判斷元素是否存在 def isElementPresent(self, by, value): try: element =self.driver.find_element(by=by, value=value) except NoSuchElementException as e: # 發生了NoSuchElementException異常,說明頁面中未找到該元素,返回False return False else: # 沒有發生異常,表示在頁面中找到了該元素,返回True return True