Issue
Please see the following element:
<div class="success"><button class="close" data-dismiss="alert" type="button">×</button>
User 'MyUser' deleted successfully</div>
Find my element:
driver.findElement(By.cssSelector("div.success")
So after found this div
and get the text using selenium with getText
or getAttribute("innerHTML")
the return:
×
User 'MyUser' deleted successfully
How can I get only the last line without this x
?
Solution
The text you want is present in a text node and cannot be retrieved directly with Selenium since it only supports element nodes.
You could remove the beginning:
String buttonText = driver.findElement(By.cssSelector("div.success > button")).getText();
String fullText = driver.findElement(By.cssSelector("div.success")).getText();
String text = fullText.substring(buttonText.length());
You could also extract the desired content from the innerHTML
with a regular expression:
String innerText = driver.findElement(By.cssSelector("div.success")).getAttribute("innerHTML");
String text = innerText.replaceFirst(".+?</button>([^>]+).*", "$1").trim();
Or with a piece of JavaScript code:
String text = (String)((JavascriptExecutor)driver).executeScript(
"return document.querySelector('div.success > button').nextSibling.textContent;");
Answered By - Florent B.
Answer Checked By - Robin (JavaFixing Admin)