1. 程式人生 > >selenium--判斷頁面元素是否存在

selenium--判斷頁面元素是否存在

屬性 表示 訪問 .com www. 元素 url false 是否


用於測試的網址:
http://www.sogou.com
調用API的實例代碼:
def isElementPresent(self,by,value):
#從selenium.common.exceptions 模塊導入 NoSuchElementException類
from selenium.common.exceptions import NoSuchElementException
try:
element = self.driver.find_element(by = by, value= value)
#原文是except NoSuchElementException, e:

except NoSuchElementException as e:
#打印異常信息
print(e)
#發生了NoSuchElementException異常,說明頁面中未找到該元素,返回False
return False
else:
#沒有發生異常,表示在頁面中找到了該元素,返回True
return True

def test_isElementPresent(self):
url = "http://www.sogou.com"
#訪問sogou首頁
self.driver.get(url)

#判斷頁面元素ID屬性值為"query"的頁面元素是否存在
res = self.isElementPresent(‘id‘,‘query‘)
if res is True:
print(u‘所查找的元素存在於頁面上‘)
else:
print(u‘頁面中未找到所需要的元素‘)
摘自《Selenium WebDriver 3.0自動化測試框架實戰指南》--吳曉華 王晨昕 編著

selenium--判斷頁面元素是否存在