Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Does WebElement.equals() Method Check for Equality?

Tags:

I have more than 1 XPath pointing to a web element and I want to determine if both elements are equivalent (i.e, if I perform the action sendKeys() or click() on both web elements the action would be executed on the same web element) Currently I'm checking for equality using the following method:

    WebElement element1 = driver.findElement(By.xpath(".//*[@id='ap_email']"));
    WebElement element2 = driver.findElement(By.xpath(".//*[@type='email']"));


    System.out.println(element1.equals(element2));

This will return true as long as both XPath point to the same element.

However, I am unsure how the method determines equality? And are there any circumstances where the two web elements are in fact the same (i.e, any action carried out on them would be carried out on the same web element) but the method shows they are different? Or vice versa?

I am trying to develop a foolproof method to determine equality of two web elements.

I'm using Java and Selenium.

like image 628
ee clipse Avatar asked Aug 17 '16 17:08

ee clipse


1 Answers

However, I am unsure how the method determines equality?

The driver generates a reference for each encountered HTMLElement object in the document and always returns the same reference for an HTMLElement object.

This reference is stored in the WebElement.id property on the client side and has nothing to do with the id attribute used with a locator.

So to determine the equality between two WebElement, the client simply tests the reference stored in WebElement.id.

And are there any circumstances where the two web elements are in fact the same but the method shows they are different?

Technically speaking, no it never happens and it would be a serious issue if it was the case.

But it kind of depends on what you mean by the same. For instance a button can look the same at two different moments, but may have been replaced by an identical one which would generate a new reference. This is the case when the page or some parts are reloaded:

  driver.get("http://stackoverflow.com/");

  WebElement elementA = driver.findElement(By.cssSelector("#logo"));
  WebElement elementB = driver.findElement(By.cssSelector("#logo"));

  boolean same1 = elementA.equals(elementB);  // return true

  elementB.click();  // reloads the page, all the previous web element are now obsolete

  WebElement elementC = driver.findElement(By.cssSelector("#logo"));

  boolean same2 = elementA.Equals(elementC);  // return false
like image 88
Florent B. Avatar answered Sep 26 '22 16:09

Florent B.