html – Fetch a particular String in <div> using xpath-ThrowExceptions

Exception or error:

I have the following DOM structure / HTML:

<div class = "something" >
    <div>
        <span>Some text</span>
    </div>
"Automated Script"
</div>

I am testing using Selenium Webdriver and have to fetch the string Automated Script to do an Assert.

Assert.assertEquals("Automated Script",webDriver.findElement(By.xpath("/div")).getText());

But the above xpath fetches both Some Text and Automated Script.
Is there a way to only get the string Automated Script?

How to solve:

With assertEquals:

String divText = webDriver.findElement(By.cssSelector("div.something")).getText();
String spanText = webDriver.findElement(By.cssSelector("div.something span")).getText();
String expectedText = divText.replace(spanText, "").strip();
Assert.assertEquals("Automated Script", expectedText);

With contains and asserTrue:

Assert.assertTrue(webDriver.findElement(By.cssSelector("div.something")).getText().contains("Automated Script"));

Using WebDriverWait, that will wait for text and through an error:

new WebDriverWait(driver, 5)
        .until(ExpectedConditions
                .textToBePresentInElementLocated(By.cssSelector("div.something"), "Automated Script"));

###

Yes, there is work around to execute text() in xpath in selenium. Directly it won’t work in selenium

Use evaluate() method of JavaScript and evaluate your xpath using JavascriptExecutor

JavascriptExecutor js = (JavascriptExecutor)driver;
Object message = js.executeScript("var value = document.evaluate(\"//div[@class='something']/text()\",document, null, XPathResult.STRING_TYPE, null ); return value.stringValue;");
System.out.println(message.toString().trim());

Leave a Reply

Your email address will not be published. Required fields are marked *