判断文本
在做结果判断的时候,经常想判断某个元素中是否存在指定的文本,如登录后判断页面中是账号是否是该用户的用户名。
在前面的登录案例中,写了一个简单的方法,但不是公用的,在 EC 模块有个方法是可以专门用来判断元素中存在指定文本的:
text_to_be_present_in_element。
另外一个差不多复方法判断元素的 value 值:
text_to_be_present_in_element_value。
源码分析
class text_to_be_present_in_element(object):
""" An expectation for checking if the given text is present in the specified element.locator, text"""
'''翻译:判断元素中是否存在指定的文本,参数:locator, text'''
def __init__(self, locator, text_):
self.locator = locator
self.text = text_
def __call__(self, driver):
try:
element_text = _find_element(driver,
self.locator).text
return self.text in element_text
except StaleElementReferenceException:
return False
1.翻译:判断元素中是否存在指定的文本,两个参数:locator, text
2.__call__里返回的是布尔值:Ture 和 False
判断文本
1.判断百度首页上,“糯米”按钮这个元素中存在文本:贴吧
2.locator 参数是定位的方法
3.text 参数是期望的值
4.失败案例,如果判断失败就会返回false
判断value
class text_to_be_present_in_element_value(object):
"""An expectation for checking if the given text is present in the element's locator, text """
def __init__(self, locator, text_):
self.locator = locator
self.text = text_
def __call__(self, driver):
try:
element_text = _find_element(driver,
self.locator).get_attribute("value")
if element_text:
return self.text in element_text
else:
return False
except StaleElementReferenceException:
return False
1.这个方法跟上面的差不多,只是这个是判断的 value 的值
2.这里举个简单案例,判断百度搜索按钮的 value 值
参考代码:
# coding:utf-8 from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.get("https://www.baidu.com/") locator = ("name", "tj_trtieba") text = u"贴吧" result = EC.text_to_be_present_in_element(locator, text)(driver) print result # 判断失败案例 locator1 = ("name", "tj_trtieba") text1 = u"贴吧hh" result1 = EC.text_to_be_present_in_element(locator1, text1)(driver) print result1 # 判断value值 locator2 = ("id","su") value = u"百度一下" result2 = EC.text_to_be_present_in_element_value(locator2,value)(driver) print result2