Selenium2+python自动化49-判断文本(text_to_be_present_in_element)
前言
在做结果判断的时候,经常想判断某个元素中是否存在指定的文本,如登录后判断页面中是账号是否是该用户的用户名。
在前面的登录案例中,写了一个简单的方法,但不是公用的,在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参数是期望的值
三、失败案例
1.如果判断失败,就返回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()
url = "https://www.baidu.com"
driver.get(url)
locator = ("name", "tj_trnuomi")
text = u"糯米"
result = EC.text_to_be_present_in_element(locator, text)(driver)
print result
#
# 下面是失败的案例
text1 = u"糯米网"
result1 = EC.text_to_be_present_in_element(locator, text1)(driver)
print result1
locator2 = ("id", "su")
text2 = u"百度一下"
result2 = EC.text_to_be_present_in_element(locator2, text2)(driver)
print result2