selenium--判断页面元素是否存在


用于测试的网址:
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自动化测试框架实战指南》--吴晓华 王晨昕 编著
posted @ 2018-11-22 17:33  sobbing_child  阅读(10818)  评论(0编辑  收藏  举报