简体   繁体   中英

How to find text on a webpage and get its XPath or CSS with Selenium and Java

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.

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 ac: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.

如果可以通过文本识别项目,则已经有一个XPath: //*[contains(., 'Itemx')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM