1

<ul id="name" class="abc">
  <li class="def">
     <a class="ghi">
       <i style="background-color: transparent;">Welcome {{username}} </i>
     </a>
  </li>
</ul>

Selenium IDE:

storeText         //ul[@id="name"]/li/a/i       a
echo              ${a}

The text "Welcome {{username}}" is displayed correctly.

However, in Selenium WebDriver, I am not able to get the text.

driver.findElement(By.xpath("//ul[@id='name']/li/a/i")).getText();

The above line of code returns an empty value.

6
  • 1
    see this stackoverflow.com/questions/18637032/… Commented Mar 3, 2017 at 5:05
  • 1
    WebElement.getText() does not work for me. I am using Chrome browser. However I can get the text using Selenium IDE in Firefox browser. Commented Mar 3, 2017 at 5:11
  • Share Html not an image. Commented Mar 3, 2017 at 5:19
  • try /ul[@id='name']/li/a/i instead of //ul[@id='name']/li/a/i and see. Commented Mar 3, 2017 at 5:25
  • @SuchitKumar, Unable to locate element Commented Mar 3, 2017 at 5:43

3 Answers 3

3

Just identify your element and simply use getAttribute("value");. Store it in a string variable and print that variable.

Code:

WebElement element = driver.findElement(By.xpath(".//input[@id='password_2']"));
String str = element.getAttribute("value");
System.out.println("value:" + str);

It worked for me

getAttribute("value").

Always try to pass the value attribute.

Sign up to request clarification or add additional context in comments.

Comments

0

First of all, you need to get the text using any locators (here I am using XPath) and set it as a string for later use. The code below will store the text contained within the XPath.

String nameOfStringGoesHere;
nameOfStringGoesHere=driver.findElement(By.xpath("//ul[@id="name"]/li/a/i ")).getText();`

To assert against the stored text later on in your script:

Assert.assertTrue("What you want your error message to appear as...!", nameOfStringGoesHere.contains("What you want to assert"));

In this example, it will get the text stored within the XPath expression, and check to see if the value is "What you want to assert", if it isn't, then it will throw the error message of "What you want your error message to appear as...!"

Comments

0

I have had exactly the same symptom in different, but similar use cases. To me, the way proposed in the question is the correct one. But indeed it returns an empty string when using the Google Chrome webdriver and the correct result with the gecko webdriver. It seems more like a bug in the Chrome webdriver(?).

(My versions: Chrome driver: 2.42. Gecko driver: 0.21)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.