Objective
In the judgment of the results, often want to determine whether an element exists in the specified text, such as the login to determine whether the account is the user's user name.
In the previous login case, a simple method was written, but not common, in the EC module there is a method that can be specifically used to determine the element in the existence of the specified text: text_to_be_present_in_element.
Another way to determine the value of an element of almost complex method: Text_to_be_present_in_element_value.
First, source code analysis
Class Text_to_be_present_in_element (object):
"" "an expectation for checking if the given text was present in the
Specified element.
Locator, text
"""
"' Translation: Determines whether the specified text exists in the element, parameter: 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. Translation: Determines whether the specified text exists in the element, two parameters: Locator, text
Boolean value returned in 2.__call__: Ture and False
Second, judge the text
1. Judging Baidu homepage, "glutinous rice" button in this element exists text: glutinous rice
2.locator parameter is the method of locating
The 3.text parameter is the desired value
Three, failure cases
1. If the judgment fails, return false
Iv. Methods of Judging value
Class Text_to_be_present_in_element_value (object):
"""
An expectation for checking if the given text was 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. This method is the same as above, but this is the value of the judgment
2. Here is a simple case to determine the value of Baidu Search button
V. Reference code
# 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 "glutinous rice"
result = Ec.text_to_be_present_in_element (locator, text) (driver)
Print result
# QQ Group: 232607095
# Below is a case of failure
Text1 = u "Sticky rice net"
RESULT1 = ec.text_to_be_present_in_element (Locator, Text1) (driver)
Print RESULT1
Locator2 = ("id", "su")
Text2 = u "Baidu a bit"
RESULT2 = Ec.text_to_be_present_in_element_value (Locator2, Text2) (driver)
Print RESULT2
Selenium2+python Automation 49-Judging text (text_to_be_present_in_element) "Reprint"