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")>
Edit:
the use of !=
instead of is not
would have resolved everything:
if self.first_input != self.input_fields[0]:
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
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