Search code examples
pythonseleniumpycharmassert

How to validate whether the text of web elements matches in Selenium Python?


I have been working on a project where I need to assert text of web elements in Selenium Python. Below is the example of what I meant:

Example

enter image description here

what I want to assert is the value 6.00 of the far-right of the image and the $6.00 of the bottom-left of the image.

Example.py

class Example:

    def checkValue(self):
       element 1 = self.driver.find_element_by_xpath("//div[contains(text(),'6.00')]")
       element 2 = self.driver.find_element_by_xpath("//label[contains(text(),'Total Amount: $6.00')]")

Test.py

class Test:

    def test_1:
        np = new Example()
        np.checkValue()

I have included the blueprint for the 2 elements. May I know how to include assert command in this example.py program?


Solution

  • You should either check if both elements may be found with the given price, or you can check whether the given elements have the expected value.

    Option1

    Find elements by price and let selenium raise the exception:

    def check_value(self, expected_price):
        elem1_xp = '//tr[@whatever]//td[contains(text(),"%s")]' % expected_price # xpath of the subtotal price element, adjust it
        elem2_xp = '//div[contains(text(), "Total amount: $%s")]' % expected_price # xpath of the total element, adjust it
        element_1 = self.driver.find_element_by_xpath(elem1_xp)
        element_2 = self.driver.find_element_by_xpath(elem2_xp)
    

    With this solution, when element_1 or element_2 can't be found, an Exception will be raised and you will see which element couldn't be found. You don't need an assert here. If both elements are found, the check is passed.

    If you are searching for 6.00 and it is present twice on the screen, you need to be careful to avoid finding the same element twice (or the element and its parent).

    Option2

    Check if the value of the two elements match. The first and most important thing here is to have a precise xpath for both elements.

    def check_value(self, expected_price):
        elem1_xp = '//tr[@whatever]//td[4]' # precise xpath of the subtotal price element
        elem2_xp = '//div[contains(text(), "Total amount: $")]' # total price element
        element_1_value = self.driver.find_element_by_xpath(elem1_xp).text
        element_2_value = self.driver.find_element_by_xpath(elem2_xp).text.replace("Total amount: $", "")
        assert element_1_value == element_2_value == expected_price, "Price mismatch! Expected price is %s, subtotal is %s, total price is %s" % (expected_price, element_1_value, element_2_value)