3

I have a button, clicking on it generates a number which is wrapped in paragraph text such as <p>random number <p> , I want to get that random number value and do operations based on number it generates.

From below I need to get 34,756 number and store it in Java.

Here is the HTML code for it:

<div class="form-group">
<div class="alert alert-count">
  <p>
  <b>
<!-- react-text: 531 -->
<!-- /react-text -->
<!-- react-text: 532 -->
 34,756
<!-- /react-text -->
</b>


And the XPath I used is as below:

String count = driver.findElement(By.xpath("//div[@class='alert alert-count']/p).getText();

But on console it gives error as:

Exception in thread "main" java.lang.NullPointerException

2

Your example code is missing a " and a ) in the By.xpath. Guess you would get a syntaxError so your real code might be correct.

Do you wait for the element, because I think the findElement returns no object ( e.g. NULL) when it is not displayed (yet) and called getText() on a NULL is not possible , resulting in the NullPointerException. Read: https://stackoverflow.com/questions/20903231/how-to-wait-until-an-element-is-present-in-selenium

Keep in mind findElement does not wait for the element, it just fails instantly.

1

I think the there is a problem with the provided XPath, you are navigating to the paragraph tag (<p> tag) and fetching the text, I suggest you navigate to the bold tag (<b>tag) and fetch the respective value, like the following:

String count = driver.findElement(By.xpath("//div[@class='alert alert-count']/p/b")).getText();
  • I think this should work – Sagar007 May 2 '17 at 9:00
  • Are you sure? In the C# bindings, the Text property gets ALL innerHTML, even from child nodes. – FDM May 2 '17 at 9:51
  • @FDM What you have said is also true. As Neils, Mentioned the syntax error may also be the case – the_coder May 3 '17 at 3:42
0

We are providing test automation services to clients and we have tried the below code for getting text of HTML tag:-

String count = driver.findElement(By.xpath("//div[@class='alert alert-count']/p).getAttribute("innerhtml");          //getting text from HTML
    System.out.println(count);              //printing the text
0

you can get the text for an HTML tag using the below snippet

String count = driver.findElement(By.xpath("//div[@class='alert alert-count']/p).getAttribute("innerhtml");

System.out.println(count); 

It will fetch the text inside the HTML and prints it to console.

Not the answer you're looking for? Browse other questions tagged or ask your own question.