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
# 交流QQ群:232607095
# 下面是失敗的案例
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_value(locator2, text2)(driver)
print result2
Selenium2+python自動化49-判斷文本(text_to_be_present_in_element)【轉載】