Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium - Check if a WebElement is equal to another WebElement

How to compare two selenium WebElements to see if they are the same ?

First I retrieve a list of input_fields and the first_input element:

self.input_fields = driver.find_elements(By.CLASS_NAME, class_name) self.first_input = driver.find_element(By.ID, id)

Then I try to check if input_fields[0] and first_input are the same WebElement.

if self.first_input is not self.input_fields[0]:
    self.__log.warning("WebElement first_input : {} != {}".format(self.first_input, self.input_fields[0]))

Though the session and element are the same, the warning message is in any case triggered.

WARNING  - WebElement first_input: <selenium.webdriver.remote.webelement.WebElement (session="796bf0bcf3e0df528ee932d477951689", element="94a2ee62-9511-45e5-8aa3-bd3d3e9be309")> != <selenium.webdriver.remote.webelement.WebElement (session="796bf0bcf3e0df528ee932d477951689", element="94a2ee62-9511-45e5-8aa3-bd3d3e9be309")>
like image 969
Marco D.G. Avatar asked Dec 27 '25 14:12

Marco D.G.


1 Answers

Edit: the use of != instead of is not would have resolved everything:

if self.first_input != self.input_fields[0]:

Solution

if self.first_input.id == self.input_fields[0].id:
    self.__log.info("Same element {} , {}".format(self.first_input.id, self.input_fields[0].id))

Reading the docs I've found the id property, whose definition serves as getter for the private attribute_id

@property
def id(self):
    """Internal ID used by selenium.

    This is mainly for internal use. Simple use cases such as checking if 2
    webelements refer to the same element, can be done using ``==``::

        if element1 == element2:
            print("These 2 are equal")

    """
    return self._id

source

class WebElement(object):
    def __init__(self, parent, id_, w3c=False):
        self._parent = parent
        self._id = id_
        self._w3c = w3c

Note:

print("{}".format(self.first_input.id))

Gives us the element id which is the same that we have seen in the object.

94a2ee62-9511-45e5-8aa3-bd3d3e9be309
like image 71
Marco D.G. Avatar answered Dec 30 '25 03:12

Marco D.G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!