How to get webelement text using selenium

See the following elements:

<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 finding the div and getting the text using selenium and gettext or getattribute ("innerHTML"), return:

×
User 'MyUser' deleted successfully

So my question is how to get only the last line without this X

Solution

The text you want exists in the text node and cannot be retrieved directly using selenium because it only supports element nodes

You can delete 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 can also use regular expressions to extract the required content from innerHTML:

String innerText = driver.findElement(By.cssSelector("div.success")).getAttribute("innerHTML");
String text = innerText.replaceFirst(".+?</button>([^>]+).*","$1").trim();

Or use a piece of javascript:

String text = (String)((JavascriptExecutor)driver).executeScript(
    "return document.querySelector('div.success > button').nextSibling.textContent;");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>