views:

244

answers:

3

Is there a way to return the xpath of an element in Selenium during runtime whos xpath changes every time you return to the page? I need to extract a random number from the xpath of the element.

Ex: //div[@id='element_id-87462'] where 87462 is a new random number everytime the element is loaded. I want to be able to extract 87462 so I can identify the object.

+2  A: 

Use the xpath contains() function.

storeAttribute | //div[contains(text(),'your known text here')]@id | myid
echo | ${myid}

If you want just the number portion, add some javascript and replace the "element_id-" portion.

storeAttribute | //div[contains(text(),'your known text here')]@id | myid
storeEval | var number = "${myid}".replace("element_id-","");number; | numid
echo | ${myid}
echo | ${numid}
s_hewitt
Thank you for your response but the problem I am having is I need to retrieve this element from a list of elements with the same xpath id (minus the random #). I know the text of this element, is there a way to return the xpath of an element where I know the text inside the element.
TesterGuy
Updated to be based on known text inside element.
s_hewitt
+1  A: 

Sidenote: Question sounds like OP is using Wicket, which (semi-randomly) generates element IDs. We've found that the approach to overwrite Wicket's behaviour and use our own ID generator, which is deterministic, more practical for testability.

mhaller
A: 

It sounds like you need to use getAttribute to retrieve the "id" attribute of the div. Take a look at:

As an aside, xpath is what you are using to find the element or find the attribute, but you are not really interested in the xpath itself, what you are interested in is the id attribute on the div.

Tom E