Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get WebElement text with selenium

Tags:

java

selenium

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

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

like image 463
david hol Avatar asked May 18 '16 11:05

david hol


People also ask

How can we get a text of a Webelement in Selenium?

We can get the text from a website using Selenium webdriver USING the getText method. It helps to obtain the text for a particular element which is visible or the inner text (which is not concealed from the page).

How do I get HTML text in Selenium?

New Selenium IDE We can get the innerHTML attribute to get the source of the web element. The innerHTML is an attribute of a webelement which is equal to the text that is present between the starting and ending tag. The get_attribute method is used for this and innerHTML is passed as an argument to the method.


2 Answers

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:

String text = (String)((JavascriptExecutor)driver).executeScript(
    "return document.querySelector('div.success > button').nextSibling.textContent;");
like image 73
Florent B. Avatar answered Sep 21 '22 03:09

Florent B.


WebElement element = driver.findElement(By.className("div.success")
element.getText();

shall help you get the text of the div

like image 44
Naman Avatar answered Sep 24 '22 03:09

Naman