Get error [object Text]. It should be an element

Trying to get the text from the div with xPath. Finds information in the browser good, but when i try to run with an idea than i get error:"is: [object Text]. It should be an element."

       List<WebElement> priceGameWebElement =  webDriver.findElements(By.xpath("//div[contains(@class,'search_price')]" +
            "/text()[normalize-space()][1]"));

What do I need to do to make everything work?

Upvotes: 0

Views: 1766

Answers (2)

Viktor Ilienko
Viktor Ilienko

Reputation: 895

If for some reason you cannot exclude text() from XPath and you need just extract the text of the element, then there is a workaround: use method document.evaluate() from JavaScript.

Code example:

    String textObjectXpath = "\"//*[local-name() = 'text'][@x='8']/text()\"";
    String script = "var element = document.evaluate("
            + textObjectXpath
            + ", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;"
            + "if (element) {return element.nodeValue;}";
    String extractedText = (String) ((JavascriptExecutor)driver).executeScript(script);

The if statement "if (element) {return element.nodeValue;}" could be omitted if you don't care about the scenario when the element will be without text. In a such case, you may want to replace the line with "return element.nodeValue;"

Upvotes: 0

zx485
zx485

Reputation: 29022

You can "interrupt" your query before the /text()... part like this:

List<WebElement> priceGameWebElement =  webDriver.findElements(By.xpath("//div[contains(@class,'search_price')]"));

Then you should get a List<WebElement> which contains the elements with the text() nodes for further distinction. They could probably be queried with the .getText() function.

Upvotes: 1

Related Questions