Haithem Kefi
Haithem Kefi

Reputation: 11

Unable to locate an element even when the xpath is correct

enter image description here

i'm tried to select an element from an auto suggestion field but i got always an error saying that the element could not be found even that i'm sure my xpath is correct

here's my code :

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class=\"ui-menu-item-with-icon ui-menu-item\"][1]")));

driver.findElement(By.xpath("//*[@class=\"ui-menu-item-with-icon ui-menu-item\"][1]")).click();

it should find //*@class=\"ui-menu-item-with-icon ui-menu-item\" which is the first suggestion albert cammus

here's the outerHtml

<li class="ui-menu-item-with-icon ui-menu-item" role="menuitem">
  <a class="ui-corner-all" tabindex="-1">
    <span class="item-icon"></span>
    Albert Camus (SARCELLES)</a>
</li>"

Upvotes: 0

Views: 97

Answers (2)

Dmitri T
Dmitri T

Reputation: 168002

Your XPath is more or less OK apart from using wildcard which may result into longer processing so you can go for li instead of *.

Another option is sticking to the <a> tag containing the text you would like to click using normalize-space() function something like:

//a[normalize-space()="Albert Camus (SARCELLES)"]

enter image description here

Also your popup may reside within an iframe so you might have to switch the webdriver context to the relevant iframe element.

Upvotes: 1

cruisepandey
cruisepandey

Reputation: 29362

Why don't you try linkText over Xpath ?

linkText is more stable then Xpath, there's no doubt about that.

Code :

wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Albert Camus (SARCELLES)")));  

I'm not very sure about spaces in your HTML, that's the reason why I have used partialLinkText

Upvotes: 0

Related Questions