Reputation: 41
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?
Upvotes: 0
Views: 171
Reputation: 7708
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());
Upvotes: 0
Reputation: 12255
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"));
Upvotes: 1