0

There is a page that lists items on a dynamic table. The order and the number of items on the table changes randomly.

I would like to find one of the items "Itemx" based on the text "Itemx" and then get and use its XPath or CSS in another part of the code.

I can find the element based on the text "Itemx"

driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Itemx[\\s\\S]*$");

But how can I get its XPath or CSS?

I can't seem to find anything on the web. Everything out there shows you how to verify or find the text using XPath. For me it's the opposite. I have the text and I want to find its XPath.

3 Answers 3

3

Both XPath and CSS selectors are arbitrary. There is no good answer for this in the general case.

Selecting the first c in <a><b></b><c></c><c></c></a> with a CSS selector might be c:first-of-type, or a > c:nth-child(2), or a c:first-of-type, or a > b + c, or a number of other things. Similarly as an XPath there are many ways of representing it. If you change the markup, what should happen?

It all depends upon the context, the stability required, whether false positives or false negatives are worse (you can make it very strict so that if the markup changes it will probably break, or you can make it very loose so that if the markup changes you may well select the wrong thing) and the whim of the person doing it. (Which of the ways above will I select? Eeny, meeny, miny, mo...)

If, however, you only care about the current state of a document and have no need for resilience, first of all consider if you actually need to have such a selector. You can probably pass the DOM element around instead. If you want to uniquely identify an element, though, following through the DOM tree is going to be a fairly straightforward way, travelling down level by level, observing which child the node is. You'll end up with something like this:

:root > :nth-child(3) > :nth-child(1) > :nth-child(4)

Ugly, but it may be what you want.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for a great description. I usually tell people that "XPath and CSS locators are like driving directions, not addresses. Both techniques get you to the same place, but only the latter identifies the place uniquely."
1

If you can identify the item by its text, you already have an XPath for it: //*[contains(., 'Itemx').

Comments

0

There's an add-on for Firefox's firebug called Firepath. Basically with it installed, you right click on any element on a page and select: inspect in FirePath. You can also run your tests in here too, if you're trying to modify the XPATH or CSS SELECTOR path shorter, etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.