Selenium2+python自動化49-判斷文本(text_to_be_present_in_element)

前言java

在作結果判斷的時候,常常想判斷某個元素中是否存在指定的文本,如登陸後判斷頁面中是帳號是不是該用戶的用戶名。python

在前面的登陸案例中,寫了一個簡單的方法,但不是公用的,在EC模塊有個方法是能夠專門用來判斷元素中存在指定文本的:text_to_be_present_in_element。web

另一個差很少複方法判斷元素的value值:text_to_be_present_in_element_value。源碼分析

 

1、源碼分析學習

class text_to_be_present_in_element(object):
    """ An expectation for checking if the given text is present in the
    specified element.
    locator, text
    """url

    '''翻譯:判斷元素中是否存在指定的文本,參數: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 Falsespa

1.翻譯:判斷元素中是否存在指定的文本,兩個參數:locator, text翻譯

2.__call__裏返回的是布爾值:Ture和False3d

 

2、判斷文本blog

1.判斷百度首頁上,「糯米」按鈕這個元素中存在文本:糯米

2.locator參數是定位的方法

3.text參數是指望的值

 

3、失敗案例

1.若是判斷失敗,就返回False

 

4、判斷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值

 

5、參考代碼

# 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

 

 

學習過程當中有遇到疑問的,能夠加selenium(python+java) QQ羣交流:646645429

以爲對你有幫助,就在右下角點個贊吧!

 selenium+python高級教程》已出書:selenium webdriver基於Python源碼案例

(購買此書送對應PDF版本)

 

相關文章
相關標籤/搜索