Riy1234
Riy1234

Reputation: 39

Unable to find Dynamic Xpath

My xpath is :

//*[@id='form_MenuBar:j_id24']/span

and the value # 24 changes.

//*[@id='form_MenuBar:j_id48']/span

I tried but doesn't works.

driver.findElement(By.xpath("//a[contains(@id,'form_MenuBar:j_id$')]/span"));

Source XML:

<li class="ui-menuitem ui-widget ui-corner-all ui-menuitem-active" role="menuitem">
  <a id="form_MenuBar:j_id24" class="ui-menuitem-link ui-corner-all ui-state-hover" href="/Demand/j_spring_security_logout">
    <span class="ui-menuitem-text">Log off</span>
  </a>
</li>

Upvotes: 1

Views: 1180

Answers (2)

Greg A.
Greg A.

Reputation: 309

It appears that you are using java so I'll try to answer it based on that. I'm not a java developer so I apologize if it's not syntactically correct.

If all that is changing is the number within the ID, and you know the ID, you could do:

driver.findElement(By.id(String.format("form_MenuBar:j_id%d", the_id));

Also, I'm not sure about your application that you are testing, but if there are multiple elements that have an id beginning with "form_MenuBar:j_id", then findElement will only find the first one, which might not be the link you are attempting to find.

you could use findElements which will return a list of all elements that match that and then iterate through those until you find the one you really want.

Upvotes: 0

Arun
Arun

Reputation: 875

Just try

driver.findElement(By.xpath("//a[contains(@id,'form_MenuBar:j_id')]/span"));

If you are using contains in xpath no need to use '$'.

Upvotes: 2

Related Questions